Tonic commited on
Commit
654a165
·
1 Parent(s): 6655309

qol improvements, layout, market open/close

Browse files
Files changed (1) hide show
  1. app.py +47 -2
app.py CHANGED
@@ -13,6 +13,7 @@ from typing import Dict, List, Tuple, Optional
13
  import json
14
  import spaces
15
  import gc
 
16
 
17
  # Initialize global variables
18
  pipeline = None
@@ -44,6 +45,31 @@ def load_pipeline():
44
  print(f"Error loading pipeline: {str(e)}")
45
  raise RuntimeError(f"Failed to load model: {str(e)}")
46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  def get_historical_data(symbol: str, timeframe: str = "1d", lookback_days: int = 365) -> pd.DataFrame:
48
  """
49
  Fetch historical data using yfinance.
@@ -57,6 +83,11 @@ def get_historical_data(symbol: str, timeframe: str = "1d", lookback_days: int =
57
  pd.DataFrame: Historical data with OHLCV and technical indicators
58
  """
59
  try:
 
 
 
 
 
60
  # Map timeframe to yfinance interval and adjust lookback period
61
  tf_map = {
62
  "1d": "1d",
@@ -379,6 +410,14 @@ def create_interface():
379
  gr.Markdown("# Structured Product Analysis")
380
  gr.Markdown("Analyze stocks for inclusion in structured financial products with extended time horizons.")
381
 
 
 
 
 
 
 
 
 
382
  with gr.Tabs() as tabs:
383
  # Daily Analysis Tab
384
  with gr.TabItem("Daily Analysis"):
@@ -408,10 +447,11 @@ def create_interface():
408
 
409
  with gr.Column():
410
  daily_plot = gr.Plot(label="Analysis and Prediction")
411
- daily_signals = gr.JSON(label="Trading Signals")
412
 
413
  with gr.Row():
414
  with gr.Column():
 
 
415
  gr.Markdown("### Structured Product Metrics")
416
  daily_metrics = gr.JSON(label="Product Metrics")
417
 
@@ -420,6 +460,9 @@ def create_interface():
420
 
421
  gr.Markdown("### Sector Analysis")
422
  daily_sector_metrics = gr.JSON(label="Sector Metrics")
 
 
 
423
 
424
  # Hourly Analysis Tab
425
  with gr.TabItem("Hourly Analysis"):
@@ -553,7 +596,9 @@ def create_interface():
553
  return signals, fig, product_metrics, risk_metrics, sector_metrics
554
  except Exception as e:
555
  error_message = str(e)
556
- if "Insufficient data points" in error_message:
 
 
557
  error_message = f"Not enough data available for {symbol} in {timeframe} timeframe. Please try a different timeframe or symbol."
558
  elif "no price data found" in error_message:
559
  error_message = f"No data available for {symbol} in {timeframe} timeframe. Please try a different timeframe or symbol."
 
13
  import json
14
  import spaces
15
  import gc
16
+ import pytz
17
 
18
  # Initialize global variables
19
  pipeline = None
 
45
  print(f"Error loading pipeline: {str(e)}")
46
  raise RuntimeError(f"Failed to load model: {str(e)}")
47
 
48
+ def is_market_open() -> bool:
49
+ """Check if the market is currently open"""
50
+ now = datetime.now()
51
+ # Check if it's a weekday (0 = Monday, 6 = Sunday)
52
+ if now.weekday() >= 5: # Saturday or Sunday
53
+ return False
54
+
55
+ # Check if it's during market hours (9:30 AM - 4:00 PM ET)
56
+ et_time = now.astimezone(pytz.timezone('US/Eastern'))
57
+ market_open = et_time.replace(hour=9, minute=30, second=0, microsecond=0)
58
+ market_close = et_time.replace(hour=16, minute=0, second=0, microsecond=0)
59
+
60
+ return market_open <= et_time <= market_close
61
+
62
+ def get_next_trading_day() -> datetime:
63
+ """Get the next trading day"""
64
+ now = datetime.now()
65
+ next_day = now + timedelta(days=1)
66
+
67
+ # Skip weekends
68
+ while next_day.weekday() >= 5: # Saturday or Sunday
69
+ next_day += timedelta(days=1)
70
+
71
+ return next_day
72
+
73
  def get_historical_data(symbol: str, timeframe: str = "1d", lookback_days: int = 365) -> pd.DataFrame:
74
  """
75
  Fetch historical data using yfinance.
 
83
  pd.DataFrame: Historical data with OHLCV and technical indicators
84
  """
85
  try:
86
+ # Check if market is open for intraday data
87
+ if timeframe in ["1h", "15m"] and not is_market_open():
88
+ next_trading_day = get_next_trading_day()
89
+ raise Exception(f"Market is currently closed. Next trading day is {next_trading_day.strftime('%Y-%m-%d')}")
90
+
91
  # Map timeframe to yfinance interval and adjust lookback period
92
  tf_map = {
93
  "1d": "1d",
 
410
  gr.Markdown("# Structured Product Analysis")
411
  gr.Markdown("Analyze stocks for inclusion in structured financial products with extended time horizons.")
412
 
413
+ # Add market status message
414
+ market_status = "Market is currently closed" if not is_market_open() else "Market is currently open"
415
+ next_trading_day = get_next_trading_day()
416
+ gr.Markdown(f"""
417
+ ### Market Status: {market_status}
418
+ Next trading day: {next_trading_day.strftime('%Y-%m-%d')}
419
+ """)
420
+
421
  with gr.Tabs() as tabs:
422
  # Daily Analysis Tab
423
  with gr.TabItem("Daily Analysis"):
 
447
 
448
  with gr.Column():
449
  daily_plot = gr.Plot(label="Analysis and Prediction")
 
450
 
451
  with gr.Row():
452
  with gr.Column():
453
+
454
+
455
  gr.Markdown("### Structured Product Metrics")
456
  daily_metrics = gr.JSON(label="Product Metrics")
457
 
 
460
 
461
  gr.Markdown("### Sector Analysis")
462
  daily_sector_metrics = gr.JSON(label="Sector Metrics")
463
+
464
+ gr.Markdown("### Trading Signals")
465
+ daily_signals = gr.JSON(label="Trading Signals")
466
 
467
  # Hourly Analysis Tab
468
  with gr.TabItem("Hourly Analysis"):
 
596
  return signals, fig, product_metrics, risk_metrics, sector_metrics
597
  except Exception as e:
598
  error_message = str(e)
599
+ if "Market is currently closed" in error_message:
600
+ error_message = f"{error_message}. Please try again during market hours or use daily timeframe."
601
+ elif "Insufficient data points" in error_message:
602
  error_message = f"Not enough data available for {symbol} in {timeframe} timeframe. Please try a different timeframe or symbol."
603
  elif "no price data found" in error_message:
604
  error_message = f"No data available for {symbol} in {timeframe} timeframe. Please try a different timeframe or symbol."