Agathe1489 commited on
Commit
336b1a5
·
verified ·
1 Parent(s): a636d55

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -5
app.py CHANGED
@@ -19,13 +19,33 @@ def get_stock_price(ticker: str) -> str:
19
  ticker: A string representing the stock ticker symbol (e.g., "AAPL" for Apple).
20
  """
21
 
22
- try:
 
 
 
 
 
 
 
23
  stock = yf.Ticker(ticker)
24
- hist = stock.history(period="1d") # Get 1-day historical price
25
- price = hist["Close"].iloc[-1] # Get last closing price
26
- currency = stock.fast_info.get("currency", "USD") # Alternative currency field
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
- return f"{currency} {price:,.2f}" if price != "N/A" else "Price unavailable"
29
  except Exception as e:
30
  return f"Error fetching price: {e}"
31
 
 
19
  ticker: A string representing the stock ticker symbol (e.g., "AAPL" for Apple).
20
  """
21
 
22
+ try:
23
+ # Get the current time in EST (Eastern Time Zone)
24
+ current_time = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=-5)))
25
+
26
+ # Market open and close times (EST)
27
+ market_open = current_time.replace(hour=9, minute=30, second=0, microsecond=0)
28
+ market_close = current_time.replace(hour=16, minute=0, second=0, microsecond=0)
29
+
30
  stock = yf.Ticker(ticker)
31
+ price = None
32
+ currency = stock.fast_info.get("currency", "USD")
33
+
34
+ # Check if the market is open
35
+ if market_open <= current_time <= market_close:
36
+ # Try to get live price
37
+ price = stock.fast_info.get("last_price")
38
+ else:
39
+ # Market is closed, use last closing price
40
+ hist = stock.history(period="1d")
41
+ if not hist.empty:
42
+ price = hist["Close"].iloc[-1] # Last closing price
43
+
44
+ if price is None:
45
+ return "Price unavailable"
46
+
47
+ return f"{currency} {price:,.2f}"
48
 
 
49
  except Exception as e:
50
  return f"Error fetching price: {e}"
51