DanielKiani commited on
Commit
30242ea
ยท
verified ยท
1 Parent(s): 1c44875

Update scripts/app.py

Browse files
Files changed (1) hide show
  1. scripts/app.py +215 -125
scripts/app.py CHANGED
@@ -1,5 +1,7 @@
1
  # scripts/app.py
2
 
 
 
3
  import gradio as gr
4
  import pandas as pd
5
  import numpy as np
@@ -10,38 +12,10 @@ import os
10
  import sys
11
  import json
12
  import torch
13
- import shutil
14
- import yfinance as yf
15
-
16
- # --- Fix YFinance Cache Lock ---
17
- try:
18
- cache_dir = "/tmp/pytz_cache"
19
- if os.path.exists(cache_dir): shutil.rmtree(cache_dir)
20
- os.makedirs(cache_dir, exist_ok=True)
21
- yf.set_tz_cache_location(cache_dir)
22
- except: pass
23
-
24
- # --- Add project root to sys.path ---
25
- try:
26
- script_dir = os.path.dirname(os.path.abspath(__file__))
27
- project_root = os.path.dirname(script_dir)
28
- if project_root not in sys.path:
29
- sys.path.insert(0, project_root)
30
- except NameError:
31
- project_root = os.getcwd()
32
- if project_root not in sys.path:
33
- sys.path.insert(0, project_root)
34
-
35
- print(f"Project Root set to: {project_root}")
36
-
37
- # --- Imports ---
38
- from scripts.fetch_market_data import fetch_market_data, ASSETS, FRED_IDS
39
- # Import the new analysis function instead of RAG tools
40
- from scripts.llm_analysis_rag import analyze_agent_decision, analyze_historical_segment, setup_rag_chain
41
  from stable_baselines3 import SAC
42
- # Import the environment for simulation
43
- from scripts.environment import PortfolioEnv
44
- # Import baseline functions
45
  from scripts.evaluate_baselines import buy_and_hold, equally_weighted_rebalanced
46
 
47
  # --- Configuration ---
@@ -98,7 +72,6 @@ def initialize_dashboard_data():
98
 
99
  # Initialize data at startup
100
  try:
101
- setup_rag_chain() # Initialize RAG components if needed
102
  initialize_dashboard_data()
103
  except Exception as e:
104
  print(f"Warning: Data initialization failed. Error: {e}")
@@ -114,7 +87,7 @@ def evaluate_agent_pro(env, model):
114
  """
115
  obs, info = env.reset()
116
  terminated, truncated = False, False
117
- portfolio_values = [env.initial_balance]
118
 
119
  while not (terminated or truncated):
120
  action, _states = model.predict(obs, deterministic=True)
@@ -173,11 +146,6 @@ def calculate_feature_importance(model, obs):
173
  """
174
  # Convert observation to torch tensor and enable gradient tracking
175
  obs_tensor = torch.as_tensor(obs, dtype=torch.float32, device=model.device)
176
-
177
- # Ensure batch dimension exists
178
- if obs_tensor.dim() == 1:
179
- obs_tensor = obs_tensor.unsqueeze(0)
180
-
181
  obs_tensor.requires_grad_()
182
 
183
  # Get the policy network (actor)
@@ -198,24 +166,28 @@ def calculate_feature_importance(model, obs):
198
  action_mean = actor(scaled_input)
199
 
200
  # We need a scalar output to calculate gradients against.
 
201
  target_output = action_mean.sum()
202
 
203
  # Calculate gradients of the target output with respect to the input features
204
  grad = torch.autograd.grad(outputs=target_output, inputs=scaled_input)[0]
205
  grads.append(grad)
206
 
207
- # Stack and average gradients
208
- stacked_grads = torch.stack(grads)
209
- avg_grads = (stacked_grads[:-1] + stacked_grads[1:]) / 2.0
210
- avg_grads = avg_grads.mean(dim=0)
211
 
212
  # Calculate Integrated Gradients: (input - baseline) * average_gradients
213
  integrated_grads = (obs_tensor - baseline) * avg_grads
214
 
215
- # Detach, move to cpu, flatten, and convert to numpy array
216
  importance_scores = integrated_grads.detach().cpu().numpy().flatten()
217
 
218
  # Feature Names mapping
 
 
 
 
219
  feature_names = []
220
  for i in range(WINDOW_SIZE):
221
  for asset in ASSETS:
@@ -253,72 +225,76 @@ def calculate_feature_importance(model, obs):
253
  yaxis={'categoryorder':'total ascending'},
254
  coloraxis_showscale=False,
255
  margin=dict(l=10, r=10, t=40, b=10),
256
- height=300, # Keep it compact
257
- # Style the hover labels for readability
258
- hoverlabel=dict(
259
- bgcolor="white",
260
- font_size=14,
261
- font_family="Roboto",
262
- font_color="black"
263
- )
264
  )
265
 
266
  return fig
267
 
268
  # =========================================
269
- # Tab 4 Logic: Historical Simulation
270
  # =========================================
271
 
272
  def run_historical_simulation(start_date_str, end_date_str):
 
 
 
273
  if DASHBOARD_DATA_DF is None:
274
- return go.Figure(), "Data not initialized. Please restart app.", None
275
 
276
  status_msg = "Preparing simulation..."
277
- yield go.Figure(), status_msg, None
278
 
279
  try:
 
280
  try:
281
  start_date = pd.to_datetime(start_date_str)
282
  end_date = pd.to_datetime(end_date_str)
283
  except ValueError:
284
- yield go.Figure(), "Error: Invalid date format. Use YYYY-MM-DD.", None
285
  return
286
 
287
  if start_date < DASHBOARD_DATA_DF.index.min() or end_date > DASHBOARD_DATA_DF.index.max():
288
  avail_start = DASHBOARD_DATA_DF.index.min().date()
289
  avail_end = DASHBOARD_DATA_DF.index.max().date()
290
- yield go.Figure(), f"Error: Dates out of range ({avail_start} to {avail_end}).", None
291
  return
292
 
293
  df_slice = DASHBOARD_DATA_DF.loc[start_date:end_date].copy()
294
  asset_cols_only = [c for c in ASSETS if c in df_slice.columns]
295
 
296
  if len(df_slice) < WINDOW_SIZE + 10:
297
- yield go.Figure(), "Error: Time period too short.", None
298
  return
299
 
 
300
  status_msg = "Running RL Agent simulation..."
301
- yield go.Figure(), status_msg, None
302
 
303
- env = PortfolioEnv(df_slice, WINDOW_SIZE, initial_balance=10000)
304
 
305
  if not os.path.exists(MODEL_PATH):
306
  raise FileNotFoundError(f"Model not found: {MODEL_PATH}")
307
  model = SAC.load(MODEL_PATH)
308
 
 
309
  rl_portfolio_series = evaluate_agent_pro(env, model)
310
 
311
- status_msg = "Calculating baselines..."
312
- yield go.Figure(), status_msg, None
 
313
 
314
- bnh_portfolio_series = buy_and_hold(df_slice[asset_cols_only], initial_balance=10000)
 
 
315
  bnh_portfolio_series = bnh_portfolio_series.loc[rl_portfolio_series.index[0]:]
 
316
  bnh_portfolio_series = bnh_portfolio_series / bnh_portfolio_series.iloc[0] * 10000
317
 
318
- eq_portfolio_series = equally_weighted_rebalanced(df_slice[asset_cols_only], initial_balance=10000)
319
  eq_portfolio_series = eq_portfolio_series.loc[rl_portfolio_series.index[0]:]
320
  eq_portfolio_series = eq_portfolio_series / eq_portfolio_series.iloc[0] * 10000
321
 
 
322
  fig = go.Figure()
323
  fig.add_trace(go.Scatter(x=rl_portfolio_series.index, y=rl_portfolio_series, mode='lines', name='RL Agent (SAC)', line=dict(color='#10b981', width=3)))
324
  fig.add_trace(go.Scatter(x=bnh_portfolio_series.index, y=bnh_portfolio_series, mode='lines', name='Buy & Hold (SPY)', line=dict(color='#6b7280', dash='dash')))
@@ -332,14 +308,15 @@ def run_historical_simulation(start_date_str, end_date_str):
332
  paper_bgcolor='rgba(0,0,0,0)',
333
  plot_bgcolor='rgba(0,0,0,0)',
334
  hovermode="x unified",
335
- legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
336
- hoverlabel=dict(bgcolor="white", font_size=14, font_family="Roboto", font_color="black")
337
  )
338
 
 
339
  rl_m = calculate_metrics_pro(rl_portfolio_series)
340
  bnh_m = calculate_metrics_pro(bnh_portfolio_series)
341
  eq_m = calculate_metrics_pro(eq_portfolio_series)
342
 
 
343
  def fmt(val, is_pct=True):
344
  if pd.isna(val): return "N/A"
345
  return f"{val:.2%}" if is_pct else f"{val:.2f}"
@@ -352,12 +329,16 @@ def run_historical_simulation(start_date_str, end_date_str):
352
  }
353
  metrics_df = pd.DataFrame(metrics_data)
354
 
355
- yield fig, "Simulation Complete.", metrics_df
 
 
 
 
356
 
357
  except Exception as e:
358
  import traceback
359
  traceback.print_exc()
360
- yield go.Figure(), f"Error: {str(e)}", None
361
 
362
 
363
  # =========================================
@@ -365,6 +346,7 @@ def run_historical_simulation(start_date_str, end_date_str):
365
  # =========================================
366
 
367
  def run_historical_analysis(selected_assets, period_name):
 
368
  if DASHBOARD_DATA_DF is None or not selected_assets:
369
  return go.Figure(), "Please wait for data initialization or select assets."
370
 
@@ -372,25 +354,27 @@ def run_historical_analysis(selected_assets, period_name):
372
  yield go.Figure(), status_html
373
 
374
  try:
 
375
  days = TIME_PERIODS.get(period_name, 365)
376
  cutoff_date = datetime.now() - timedelta(days=days)
377
  valid_assets = [a for a in selected_assets if a in DASHBOARD_DATA_DF.columns]
378
  if not valid_assets:
379
- yield go.Figure(), "Error: Selected assets not found."
380
  return
381
  df_filtered = DASHBOARD_DATA_DF.loc[cutoff_date:, valid_assets].copy()
382
  if df_filtered.empty:
383
- yield go.Figure(), f"No data found for: {period_name}"
384
  return
385
 
 
386
  df_normalized = df_filtered / df_filtered.iloc[0] * 100
387
  fig = px.line(df_normalized, x=df_normalized.index, y=df_normalized.columns,
388
  title=f"Performance Comparison: {period_name} (Base=100)",
389
  color_discrete_sequence=px.colors.qualitative.Bold)
390
  fig.update_layout(template="plotly_dark", paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)',
391
- yaxis_title="Normalized Price", xaxis_title="Date", legend_title_text="", hovermode="x unified",
392
- hoverlabel=dict(bgcolor="white", font_size=14, font_family="Roboto", font_color="black"))
393
 
 
394
  analysis_text = analyze_historical_segment(df_filtered, valid_assets, period_name)
395
  formatted_analysis = f"### ๐Ÿค– AI Analyst Report: {period_name}\n\n{analysis_text}"
396
  yield fig, formatted_analysis
@@ -398,14 +382,15 @@ def run_historical_analysis(selected_assets, period_name):
398
  except Exception as e:
399
  import traceback
400
  traceback.print_exc()
401
- yield go.Figure(), f"### Error: {str(e)}"
402
 
403
 
404
  # =========================================
405
- # Tab 2 Logic: Forecast & Analysis
406
  # =========================================
407
 
408
  def get_latest_data_window(window_size=30):
 
409
  print("Fetching prediction data...")
410
  lookback_days = window_size + 150
411
  end_date = datetime.now().strftime('%Y-%m-%d')
@@ -415,7 +400,7 @@ def get_latest_data_window(window_size=30):
415
  if not os.path.exists(temp_filename): raise Exception("Failed to fetch market data file.")
416
  df = pd.read_csv(temp_filename, index_col=0, parse_dates=True)
417
  df.dropna(inplace=True)
418
- if len(df) < window_size: raise Exception(f"Not enough clean data fetched.")
419
  return df.iloc[-window_size:].copy()
420
 
421
  def prepare_observation(data_window):
@@ -424,24 +409,30 @@ def prepare_observation(data_window):
424
  norm_prices = price_data / (price_data[0] + 1e-8)
425
  norm_macro = macro_data / (macro_data[0] + 1e-8)
426
  obs = np.concatenate([norm_prices, norm_macro], axis=1)
 
427
  return obs.flatten().astype(np.float32), obs.astype(np.float32), data_window
428
 
429
  def predict_and_analyze():
 
430
  status_msg = "Starting process..."
431
  loading_html = """<div style="color: #9ca3af;">๐Ÿ”„ Fetching data & running prediction...</div>"""
 
432
  yield status_msg, None, go.Figure(), loading_html
433
 
434
  try:
435
  data_window = get_latest_data_window(WINDOW_SIZE)
 
436
  flat_obs, raw_obs, df_window_for_analyst = prepare_observation(data_window)
437
 
438
  if not os.path.exists(MODEL_PATH): raise FileNotFoundError(f"Model not found: {MODEL_PATH}")
439
  model = SAC.load(MODEL_PATH)
440
 
 
441
  status_msg = "Calculating feature importance..."
442
  yield status_msg, None, go.Figure(), loading_html
443
- xai_plot = calculate_feature_importance(model, flat_obs)
444
 
 
445
  action, _ = model.predict(flat_obs, deterministic=True)
446
  exp_action = np.exp(np.asarray(action).flatten())
447
  weights = exp_action / np.sum(exp_action)
@@ -452,6 +443,7 @@ def predict_and_analyze():
452
 
453
  status_msg = "Prediction done. Running AI Risk Analysis..."
454
  analysing_html = """<div style="color: #9ca3af;">๐Ÿค– Running Qwen-2.5-3B Risk Analysis...</div>"""
 
455
  yield status_msg, alloc_df, xai_plot, analysing_html
456
 
457
  allocations_for_llm = {k: float(v) for k, v in allocations_dict.items()}
@@ -463,12 +455,18 @@ def predict_and_analyze():
463
  risk = analysis_result.get('risk_level', 'N/A').upper()
464
  just = analysis_result.get('justification', 'N/A')
465
  conf = analysis_result.get('confidence_score', 'N/A')
466
-
467
- risk_css = "color: #ef4444;" if 'HIGH' in risk else "color: #10b981;"
468
- status_bg = "#7f1d1d" if 'HIGH' in risk else "#064e3b"
469
- status_border = "#ef4444" if 'HIGH' in risk else "#10b981"
470
- status_icon = "โ›”" if 'HIGH' in risk else "๐Ÿš€"
471
- status_text = "TRADE BLOCKED: High Risk Detected" if 'HIGH' in risk else "TRADE APPROVED"
 
 
 
 
 
 
472
 
473
  report_html = f"""
474
  <div style="background-color: #1f2937; padding: 20px; border-radius: 12px 12px 0 0; border: 1px solid #374151; border-bottom: none;">
@@ -483,38 +481,53 @@ def predict_and_analyze():
483
  </div>"""
484
  else:
485
  report_html = f"""<div style="padding: 20px; background-color: #7f1d1d; color: #fca5a5; border-radius: 12px;"><h3>โŒ Analysis Failed to Parse</h3><p>{str(analysis_result)}</p></div>"""
486
-
487
  yield status_msg, alloc_df, xai_plot, report_html
488
  except Exception as e:
489
  import traceback
490
  traceback.print_exc()
491
- yield status_msg, None, go.Figure(), f"Error: {str(e)}"
 
 
 
 
492
 
493
  # =========================================
494
  # Tab 1 Logic: Live Dashboard (DUMMY DATA)
495
  # =========================================
496
  def get_dashboard_metrics():
497
  return "$135,400", "+3.07%"
 
498
  def get_portfolio_history_plot():
499
  dates = pd.date_range(start="2023-01-01", periods=100)
500
  np.random.seed(42)
501
- rl_value = 10000 * np.cumprod(1 + np.random.normal(0.001, 0.01, 100))
502
- bnh_value = 10000 * np.cumprod(1 + np.random.normal(0.0005, 0.012, 100))
 
 
503
  fig = go.Figure()
504
- fig.add_trace(go.Scatter(x=dates, y=rl_value, mode='lines', name='RL Agent', line=dict(color='#10b981', width=3)))
505
  fig.add_trace(go.Scatter(x=dates, y=bnh_value, mode='lines', name='Benchmark', line=dict(color='#6b7280', dash='dash')))
506
- fig.update_layout(title="Portfolio Net Worth (Live)", template="plotly_dark", paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', hoverlabel=dict(bgcolor="white", font_size=14, font_color="black"))
507
  return fig
 
508
  def get_current_allocation_plot():
509
- fig = px.pie(values=[0.25, 0.1, 0.3, 0.15, 0.05, 0.15], names=ASSETS+['Cash'], title="Holdings", color_discrete_sequence=px.colors.qualitative.Bold)
510
- fig.update_layout(template="plotly_dark", paper_bgcolor='rgba(0,0,0,0)', hoverlabel=dict(bgcolor="white", font_size=14, font_color="black"))
 
 
 
511
  return fig
 
512
  def get_recent_transactions():
513
- return pd.DataFrame([["2025-11-24", "SELL", "SPY", "$4,500"], ["2025-11-21", "BUY", "BTC-USD", "$1,000"]], columns=["Date", "Type", "Asset", "Value"])
 
 
514
 
515
  # =========================================
516
  # Gradio Interface
517
  # =========================================
 
518
  custom_css = """
519
  .metric-box { background-color: #1f2937; padding: 20px; border-radius: 12px; border: 1px solid #374151; text-align: center; }
520
  .metric-label { font-size: 1.1em; color: #9ca3af; margin-bottom: 5px; }
@@ -522,55 +535,132 @@ custom_css = """
522
  .disclaimer-box { background-color: #374151; padding: 15px; border-radius: 8px; border-left: 4px solid #f59e0b; color: #d1d5db; font-size: 0.9em; margin-bottom: 20px; }
523
  """
524
 
525
- # Using theme=gr.themes.Soft(...) here because we forced requirements to support it
526
- with gr.Blocks(css=custom_css, title="Deep RL Manager") as demo:
527
- gr.HTML("""<script>function f(){document.body.classList.add('dark');} f(); setTimeout(f, 500);</script>""")
 
 
 
 
 
 
528
  gr.Markdown("# ๐Ÿง  Deep RL & LLM Portfolio Manager")
529
 
530
  with gr.Tabs():
531
- with gr.TabItem("๐Ÿ“Š Dashboard"):
532
- nw, ch = get_dashboard_metrics()
533
- with gr.Row():
534
- gr.HTML(f"<div class='metric-box'><div>Net Worth</div><div class='metric-value'>{nw}</div></div>")
535
- gr.HTML(f"<div class='metric-box'><div>Change</div><div class='metric-value' style='color:#10b981'>{ch}</div></div>")
536
  with gr.Row():
537
- with gr.Column(scale=3): gr.Plot(value=get_portfolio_history_plot())
538
- with gr.Column(scale=1): gr.Plot(value=get_current_allocation_plot())
 
 
 
 
 
 
539
  with gr.Row():
540
- with gr.Column(): gr.Dataframe(value=get_recent_transactions(), label="Transactions")
 
541
 
542
- with gr.TabItem("๐Ÿ”ฎ Forecast"):
543
- btn = gr.Button("๐Ÿš€ Run Analysis", variant="primary")
544
- stat = gr.Textbox(label="Status", interactive=False)
545
  with gr.Row():
 
 
546
  with gr.Column(scale=2):
547
- alloc = gr.Dataframe(label="Allocation")
548
- xai = gr.Plot(label="XAI")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
549
  with gr.Column(scale=3):
550
- rep = gr.HTML(label="Report")
551
- btn.click(predict_and_analyze, None, [stat, alloc, xai, rep])
552
-
553
- with gr.TabItem("๐Ÿ“… Analyst"):
 
 
 
 
 
 
 
 
 
554
  with gr.Row():
555
  with gr.Column(scale=1):
556
- ticks = ASSETS + FRED_IDS.values() if DASHBOARD_DATA_DF is None else [c for c in ASSETS + list(FRED_IDS.values()) if c in DASHBOARD_DATA_DF.columns]
557
- sel = gr.Dropdown(choices=ticks, multiselect=True, label="Assets")
558
- per = gr.Dropdown(choices=list(TIME_PERIODS.keys()), value="1 Year", label="Period")
559
- btn = gr.Button("Analyze", variant="primary")
 
 
 
 
 
 
 
560
  with gr.Column(scale=3):
561
- plot = gr.Plot()
562
- out = gr.Markdown()
563
- btn.click(run_historical_analysis, [sel, per], [plot, out])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
564
 
565
- with gr.TabItem("๐Ÿ”™ Simulation"):
566
  with gr.Row():
567
- s_d = gr.Textbox(label="Start", value="2024-01-01")
568
- e_d = gr.Textbox(label="End", value="2025-01-01")
569
- btn = gr.Button("Run", variant="primary")
570
- stat = gr.Textbox(label="Status")
571
- plot = gr.Plot()
572
- met = gr.Dataframe(label="Metrics")
573
- btn.click(run_historical_simulation, [s_d, e_d], [plot, stat, met])
 
 
 
 
 
 
 
 
 
 
 
574
 
575
  if __name__ == "__main__":
576
  demo.queue().launch(server_name="0.0.0.0", server_port=7860, debug=True, share=True)
 
1
  # scripts/app.py
2
 
3
+ # scripts/app.py
4
+
5
  import gradio as gr
6
  import pandas as pd
7
  import numpy as np
 
12
  import sys
13
  import json
14
  import torch
15
+ from fetch_market_data import fetch_market_data, ASSETS, FRED_IDS
16
+ from llm_analysis_rag import analyze_agent_decision, analyze_historical_segment
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  from stable_baselines3 import SAC
18
+ from environment import PortfolioEnv
 
 
19
  from scripts.evaluate_baselines import buy_and_hold, equally_weighted_rebalanced
20
 
21
  # --- Configuration ---
 
72
 
73
  # Initialize data at startup
74
  try:
 
75
  initialize_dashboard_data()
76
  except Exception as e:
77
  print(f"Warning: Data initialization failed. Error: {e}")
 
87
  """
88
  obs, info = env.reset()
89
  terminated, truncated = False, False
90
+ portfolio_values = [env.initial_amount]
91
 
92
  while not (terminated or truncated):
93
  action, _states = model.predict(obs, deterministic=True)
 
146
  """
147
  # Convert observation to torch tensor and enable gradient tracking
148
  obs_tensor = torch.as_tensor(obs, dtype=torch.float32, device=model.device)
 
 
 
 
 
149
  obs_tensor.requires_grad_()
150
 
151
  # Get the policy network (actor)
 
166
  action_mean = actor(scaled_input)
167
 
168
  # We need a scalar output to calculate gradients against.
169
+ # Here we sum, representing overall sensitivity of the action vector.
170
  target_output = action_mean.sum()
171
 
172
  # Calculate gradients of the target output with respect to the input features
173
  grad = torch.autograd.grad(outputs=target_output, inputs=scaled_input)[0]
174
  grads.append(grad)
175
 
176
+ # Average the gradients using the trapezoidal rule approximation
177
+ avg_grads = (grads[:-1] + grads[1:]) / 2.0
178
+ avg_grads = torch.stack(avg_grads).mean(dim=0)
 
179
 
180
  # Calculate Integrated Gradients: (input - baseline) * average_gradients
181
  integrated_grads = (obs_tensor - baseline) * avg_grads
182
 
183
+ # Detach, move to cpu, and convert to numpy array
184
  importance_scores = integrated_grads.detach().cpu().numpy().flatten()
185
 
186
  # Feature Names mapping
187
+ num_assets = len(ASSETS)
188
+ num_macro = len(MACRO_COLS)
189
+
190
+ # Create feature names based on the observation structure
191
  feature_names = []
192
  for i in range(WINDOW_SIZE):
193
  for asset in ASSETS:
 
225
  yaxis={'categoryorder':'total ascending'},
226
  coloraxis_showscale=False,
227
  margin=dict(l=10, r=10, t=40, b=10),
228
+ height=300 # Keep it compact
 
 
 
 
 
 
 
229
  )
230
 
231
  return fig
232
 
233
  # =========================================
234
+ # Tab 4 Logic: Historical Simulation (UPDATED)
235
  # =========================================
236
 
237
  def run_historical_simulation(start_date_str, end_date_str):
238
+ """
239
+ Runs the RL agent on historical data and compares to baselines using professional metrics.
240
+ """
241
  if DASHBOARD_DATA_DF is None:
242
+ return go.Figure(), "Data not initialized. Please restart app.", gr.update(visible=False)
243
 
244
  status_msg = "Preparing simulation..."
245
+ yield go.Figure(), status_msg, gr.update(visible=False)
246
 
247
  try:
248
+ # 1. Validate and Slice Data
249
  try:
250
  start_date = pd.to_datetime(start_date_str)
251
  end_date = pd.to_datetime(end_date_str)
252
  except ValueError:
253
+ yield go.Figure(), "Error: Invalid date format. Use YYYY-MM-DD.", gr.update(visible=False)
254
  return
255
 
256
  if start_date < DASHBOARD_DATA_DF.index.min() or end_date > DASHBOARD_DATA_DF.index.max():
257
  avail_start = DASHBOARD_DATA_DF.index.min().date()
258
  avail_end = DASHBOARD_DATA_DF.index.max().date()
259
+ yield go.Figure(), f"Error: Selected dates outside available range ({avail_start} to {avail_end}).", gr.update(visible=False)
260
  return
261
 
262
  df_slice = DASHBOARD_DATA_DF.loc[start_date:end_date].copy()
263
  asset_cols_only = [c for c in ASSETS if c in df_slice.columns]
264
 
265
  if len(df_slice) < WINDOW_SIZE + 10:
266
+ yield go.Figure(), "Error: Time period too short for simulation.", gr.update(visible=False)
267
  return
268
 
269
+ # 2. Setup Environment and Agent
270
  status_msg = "Running RL Agent simulation..."
271
+ yield go.Figure(), status_msg, gr.update(visible=False)
272
 
273
+ env = PortfolioEnv(df_slice, WINDOW_SIZE, initial_amount=10000)
274
 
275
  if not os.path.exists(MODEL_PATH):
276
  raise FileNotFoundError(f"Model not found: {MODEL_PATH}")
277
  model = SAC.load(MODEL_PATH)
278
 
279
+ # 3. Run Simulation Loop & Get Values using Pro Function
280
  rl_portfolio_series = evaluate_agent_pro(env, model)
281
 
282
+ # 4. Calculate Baselines using Pro Functions
283
+ status_msg = "Calculating baselines and metrics..."
284
+ yield go.Figure(), status_msg, gr.update(visible=False)
285
 
286
+ # Pass only asset columns to baseline functions
287
+ bnh_portfolio_series = buy_and_hold(df_slice[asset_cols_only], initial_amount=10000)
288
+ # Realign B&H index to match RL agent's start date
289
  bnh_portfolio_series = bnh_portfolio_series.loc[rl_portfolio_series.index[0]:]
290
+ # Normalize B&H starting value to match RL agent's start
291
  bnh_portfolio_series = bnh_portfolio_series / bnh_portfolio_series.iloc[0] * 10000
292
 
293
+ eq_portfolio_series = equally_weighted_rebalanced(df_slice[asset_cols_only], initial_amount=10000)
294
  eq_portfolio_series = eq_portfolio_series.loc[rl_portfolio_series.index[0]:]
295
  eq_portfolio_series = eq_portfolio_series / eq_portfolio_series.iloc[0] * 10000
296
 
297
+ # 5. Generate Plot
298
  fig = go.Figure()
299
  fig.add_trace(go.Scatter(x=rl_portfolio_series.index, y=rl_portfolio_series, mode='lines', name='RL Agent (SAC)', line=dict(color='#10b981', width=3)))
300
  fig.add_trace(go.Scatter(x=bnh_portfolio_series.index, y=bnh_portfolio_series, mode='lines', name='Buy & Hold (SPY)', line=dict(color='#6b7280', dash='dash')))
 
308
  paper_bgcolor='rgba(0,0,0,0)',
309
  plot_bgcolor='rgba(0,0,0,0)',
310
  hovermode="x unified",
311
+ legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1)
 
312
  )
313
 
314
+ # 6. Calculate Professional Metrics Table
315
  rl_m = calculate_metrics_pro(rl_portfolio_series)
316
  bnh_m = calculate_metrics_pro(bnh_portfolio_series)
317
  eq_m = calculate_metrics_pro(eq_portfolio_series)
318
 
319
+ # Helper to format based on metric type
320
  def fmt(val, is_pct=True):
321
  if pd.isna(val): return "N/A"
322
  return f"{val:.2%}" if is_pct else f"{val:.2f}"
 
329
  }
330
  metrics_df = pd.DataFrame(metrics_data)
331
 
332
+ # Format the dataframe as a markdown table for cleaner display
333
+ metrics_md = metrics_df.to_markdown(index=False)
334
+ final_metrics_display = f"### ๐Ÿ“Š Professional Performance Metrics\n\n{metrics_md}"
335
+
336
+ yield fig, "Simulation Complete.", final_metrics_display
337
 
338
  except Exception as e:
339
  import traceback
340
  traceback.print_exc()
341
+ yield go.Figure(), f"Error during simulation: {str(e)}", gr.update(visible=False)
342
 
343
 
344
  # =========================================
 
346
  # =========================================
347
 
348
  def run_historical_analysis(selected_assets, period_name):
349
+ """Backend for Tab 3."""
350
  if DASHBOARD_DATA_DF is None or not selected_assets:
351
  return go.Figure(), "Please wait for data initialization or select assets."
352
 
 
354
  yield go.Figure(), status_html
355
 
356
  try:
357
+ # 1. Filter Data by Time Period
358
  days = TIME_PERIODS.get(period_name, 365)
359
  cutoff_date = datetime.now() - timedelta(days=days)
360
  valid_assets = [a for a in selected_assets if a in DASHBOARD_DATA_DF.columns]
361
  if not valid_assets:
362
+ yield go.Figure(), "Error: Selected assets not found in available data."
363
  return
364
  df_filtered = DASHBOARD_DATA_DF.loc[cutoff_date:, valid_assets].copy()
365
  if df_filtered.empty:
366
+ yield go.Figure(), f"No data found for the selected period: {period_name}"
367
  return
368
 
369
+ # 2. Generate Normalized Price Plot
370
  df_normalized = df_filtered / df_filtered.iloc[0] * 100
371
  fig = px.line(df_normalized, x=df_normalized.index, y=df_normalized.columns,
372
  title=f"Performance Comparison: {period_name} (Base=100)",
373
  color_discrete_sequence=px.colors.qualitative.Bold)
374
  fig.update_layout(template="plotly_dark", paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)',
375
+ yaxis_title="Normalized Price", xaxis_title="Date", legend_title_text="", hovermode="x unified")
 
376
 
377
+ # 3. Run AI Analysis
378
  analysis_text = analyze_historical_segment(df_filtered, valid_assets, period_name)
379
  formatted_analysis = f"### ๐Ÿค– AI Analyst Report: {period_name}\n\n{analysis_text}"
380
  yield fig, formatted_analysis
 
382
  except Exception as e:
383
  import traceback
384
  traceback.print_exc()
385
+ yield go.Figure(), f"### Error during analysis\n\n{str(e)}"
386
 
387
 
388
  # =========================================
389
+ # Tab 2 Logic: Forecast & Analysis (XAI)
390
  # =========================================
391
 
392
  def get_latest_data_window(window_size=30):
393
+ """Fetches latest data needed for prediction."""
394
  print("Fetching prediction data...")
395
  lookback_days = window_size + 150
396
  end_date = datetime.now().strftime('%Y-%m-%d')
 
400
  if not os.path.exists(temp_filename): raise Exception("Failed to fetch market data file.")
401
  df = pd.read_csv(temp_filename, index_col=0, parse_dates=True)
402
  df.dropna(inplace=True)
403
+ if len(df) < window_size: raise Exception(f"Not enough clean data fetched for prediction.")
404
  return df.iloc[-window_size:].copy()
405
 
406
  def prepare_observation(data_window):
 
409
  norm_prices = price_data / (price_data[0] + 1e-8)
410
  norm_macro = macro_data / (macro_data[0] + 1e-8)
411
  obs = np.concatenate([norm_prices, norm_macro], axis=1)
412
+ # Return both flattened obs for model and raw obs for XAI
413
  return obs.flatten().astype(np.float32), obs.astype(np.float32), data_window
414
 
415
  def predict_and_analyze():
416
+ """Main function for Forecast Tab."""
417
  status_msg = "Starting process..."
418
  loading_html = """<div style="color: #9ca3af;">๐Ÿ”„ Fetching data & running prediction...</div>"""
419
+ # Update to yield an empty plot for the XAI chart initially
420
  yield status_msg, None, go.Figure(), loading_html
421
 
422
  try:
423
  data_window = get_latest_data_window(WINDOW_SIZE)
424
+ # Get flattened obs for prediction and raw obs for XAI
425
  flat_obs, raw_obs, df_window_for_analyst = prepare_observation(data_window)
426
 
427
  if not os.path.exists(MODEL_PATH): raise FileNotFoundError(f"Model not found: {MODEL_PATH}")
428
  model = SAC.load(MODEL_PATH)
429
 
430
+ # --- XAI: Calculate Feature Importance ---
431
  status_msg = "Calculating feature importance..."
432
  yield status_msg, None, go.Figure(), loading_html
433
+ xai_plot = calculate_feature_importance(model, raw_obs)
434
 
435
+ # --- Prediction ---
436
  action, _ = model.predict(flat_obs, deterministic=True)
437
  exp_action = np.exp(np.asarray(action).flatten())
438
  weights = exp_action / np.sum(exp_action)
 
443
 
444
  status_msg = "Prediction done. Running AI Risk Analysis..."
445
  analysing_html = """<div style="color: #9ca3af;">๐Ÿค– Running Qwen-2.5-3B Risk Analysis...</div>"""
446
+ # Yield XAI plot along with other outputs
447
  yield status_msg, alloc_df, xai_plot, analysing_html
448
 
449
  allocations_for_llm = {k: float(v) for k, v in allocations_dict.items()}
 
455
  risk = analysis_result.get('risk_level', 'N/A').upper()
456
  just = analysis_result.get('justification', 'N/A')
457
  conf = analysis_result.get('confidence_score', 'N/A')
458
+ if 'HIGH' in risk:
459
+ risk_css = "color: #ef4444; font-weight: bold;"
460
+ status_bg = "#7f1d1d"
461
+ status_border = "#ef4444"
462
+ status_icon = "โ›”"
463
+ status_text = "TRADE BLOCKED: High Risk Detected"
464
+ else:
465
+ risk_css = "color: #10b981; font-weight: bold;"
466
+ status_bg = "#064e3b"
467
+ status_border = "#10b981"
468
+ status_icon = "๐Ÿš€"
469
+ status_text = "TRADE APPROVED"
470
 
471
  report_html = f"""
472
  <div style="background-color: #1f2937; padding: 20px; border-radius: 12px 12px 0 0; border: 1px solid #374151; border-bottom: none;">
 
481
  </div>"""
482
  else:
483
  report_html = f"""<div style="padding: 20px; background-color: #7f1d1d; color: #fca5a5; border-radius: 12px;"><h3>โŒ Analysis Failed to Parse</h3><p>{str(analysis_result)}</p></div>"""
484
+ # Final yield with all outputs including XAI plot
485
  yield status_msg, alloc_df, xai_plot, report_html
486
  except Exception as e:
487
  import traceback
488
  traceback.print_exc()
489
+ status_msg = f"Error: {str(e)}"
490
+ error_html = f"""<div style="padding: 20px; background-color: #7f1d1d; color: #fca5a5; border-radius: 12px;"><h3>โŒ Process Error</h3><p>{str(e)}</p></div>"""
491
+ # Final yield in case of error
492
+ yield status_msg, None, go.Figure(), error_html
493
+
494
 
495
  # =========================================
496
  # Tab 1 Logic: Live Dashboard (DUMMY DATA)
497
  # =========================================
498
  def get_dashboard_metrics():
499
  return "$135,400", "+3.07%"
500
+
501
  def get_portfolio_history_plot():
502
  dates = pd.date_range(start="2023-01-01", periods=100)
503
  np.random.seed(42)
504
+ rl_returns = np.random.normal(0.001, 0.01, 100)
505
+ bnh_returns = np.random.normal(0.0005, 0.012, 100)
506
+ rl_value = 10000 * np.cumprod(1 + rl_returns)
507
+ bnh_value = 10000 * np.cumprod(1 + bnh_returns)
508
  fig = go.Figure()
509
+ fig.add_trace(go.Scatter(x=dates, y=rl_value, mode='lines', name='RL Agent (Live)', line=dict(color='#10b981', width=3)))
510
  fig.add_trace(go.Scatter(x=dates, y=bnh_value, mode='lines', name='Benchmark', line=dict(color='#6b7280', dash='dash')))
511
+ fig.update_layout(title="Portfolio Net Worth (Live Tracking)", xaxis_title="Date", yaxis_title="Net Worth ($)", template="plotly_dark", paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1))
512
  return fig
513
+
514
  def get_current_allocation_plot():
515
+ labels = ASSETS + ['Cash']
516
+ values = [0.25, 0.10, 0.30, 0.15, 0.05, 0.15]
517
+ fig = px.pie(values=values, names=labels, title="Current Holdings Breakdown", color_discrete_sequence=px.colors.qualitative.Bold)
518
+ fig.update_traces(textposition='inside', textinfo='percent+label', hole=.4)
519
+ fig.update_layout(template="plotly_dark", paper_bgcolor='rgba(0,0,0,0)', legend=dict(orientation="h", yanchor="bottom", y=-0.1))
520
  return fig
521
+
522
  def get_recent_transactions():
523
+ data = [["2025-11-24", "Rebalance", "MULTIPLE", "N/A"], ["2025-11-24", "SELL", "SPY", "$4,500"], ["2025-11-24", "BUY", "TLT", "$4,200"], ["2025-11-21", "BUY", "BTC-USD", "$1,000"]]
524
+ return pd.DataFrame(data, columns=["Date", "Type", "Asset", "Approx. Value"])
525
+
526
 
527
  # =========================================
528
  # Gradio Interface
529
  # =========================================
530
+
531
  custom_css = """
532
  .metric-box { background-color: #1f2937; padding: 20px; border-radius: 12px; border: 1px solid #374151; text-align: center; }
533
  .metric-label { font-size: 1.1em; color: #9ca3af; margin-bottom: 5px; }
 
535
  .disclaimer-box { background-color: #374151; padding: 15px; border-radius: 8px; border-left: 4px solid #f59e0b; color: #d1d5db; font-size: 0.9em; margin-bottom: 20px; }
536
  """
537
 
538
+ # theme = gr.themes.Soft(primary_hue="emerald", secondary_hue="slate", neutral_hue="zinc").set(
539
+ # body_background_fill="#111827", block_background_fill="#1f2937", block_border_width="1px", block_border_color="#374151"
540
+ # )
541
+
542
+ with gr.Blocks(
543
+ # theme=theme, css=custom_css,
544
+ title="Deep RL Portfolio Manager") as demo:
545
+ gr.HTML("""<script>function forceDark(){document.body.classList.add('dark');} forceDark(); setTimeout(forceDark, 500);</script>""")
546
+
547
  gr.Markdown("# ๐Ÿง  Deep RL & LLM Portfolio Manager")
548
 
549
  with gr.Tabs():
550
+ # ================= TAB 1: DASHBOARD (RESTORED) =================
551
+ with gr.TabItem("๐Ÿ“Š Live Dashboard"):
552
+ # Metrics Row
 
 
553
  with gr.Row():
554
+ # MOVED THIS LINE INSIDE THE TAB
555
+ nw_val, dc_val = get_dashboard_metrics()
556
+ with gr.Column(elem_classes=["metric-box"]):
557
+ gr.HTML(f"<div class='metric-label'>Current Net Worth</div><div class='metric-value'>{nw_val}</div>")
558
+ with gr.Column(elem_classes=["metric-box"]):
559
+ gr.HTML(f"<div class='metric-label'>24h Change</div><div class='metric-value' style='color: #10b981;'>{dc_val}</div>")
560
+
561
+ # Main Chart row
562
  with gr.Row():
563
+ with gr.Column(scale=3):
564
+ history_chart = gr.Plot(value=get_portfolio_history_plot(), label="Net Worth History")
565
 
566
+ # Bottom Row: Allocations and Transactions
 
 
567
  with gr.Row():
568
+ with gr.Column(scale=1):
569
+ allocation_chart = gr.Plot(value=get_current_allocation_plot(), label="Current Allocation")
570
  with gr.Column(scale=2):
571
+ gr.Markdown("### Recent Transactions")
572
+ transactions_table = gr.Dataframe(value=get_recent_transactions(), interactive=False, wrap=True)
573
+
574
+ # ================= TAB 2: FORECAST (UPDATED with XAI) =================
575
+ with gr.TabItem("๐Ÿ”ฎ Forecast & AI Analysis"):
576
+ gr.Markdown("### Generate Tomorrow's Portfolio Strategy")
577
+ run_btn = gr.Button("๐Ÿš€ Run Overnight Analysis", variant="primary", size="lg")
578
+ status_output = gr.Textbox(label="System Status", placeholder="Ready...", interactive=False, lines=1)
579
+ gr.Markdown("---")
580
+
581
+ with gr.Row():
582
+ # Left Column: Allocations & XAI Plot
583
+ with gr.Column(scale=2):
584
+ gr.Markdown("### ๐Ÿ“ˆ Suggested Position")
585
+ allocation_output = gr.Dataframe(headers=["Asset", "Allocation"], datatype=["str", "str"], interactive=False)
586
+
587
+ # NEW: XAI Feature Importance Plot
588
+ gr.Markdown("### ๐Ÿง  Why did the agent choose this?")
589
+ xai_output_plot = gr.Plot(label="Top Influential Factors (XAI)", show_label=False)
590
+
591
+ # Right Column: AI Analysis Report
592
  with gr.Column(scale=3):
593
+ analysis_report_html = gr.HTML(label="AI Risk Analysis Report")
594
+
595
+ # Updated click event with new XAI output
596
+ run_btn.click(
597
+ fn=predict_and_analyze,
598
+ inputs=None,
599
+ outputs=[status_output, allocation_output, xai_output_plot, analysis_report_html]
600
+ )
601
+
602
+ # ================= TAB 3: HISTORICAL DATA ANALYST =================
603
+ with gr.TabItem("๐Ÿ“… Historical Data Analyst"):
604
+ gr.Markdown("### Analyze Past Market Performance with AI")
605
+
606
  with gr.Row():
607
  with gr.Column(scale=1):
608
+ all_tickers_hist = ASSETS + list(FRED_IDS.values())
609
+ if DASHBOARD_DATA_DF is not None:
610
+ available_tickers_hist = [t for t in all_tickers_hist if t in DASHBOARD_DATA_DF.columns]
611
+ else:
612
+ available_tickers_hist = []
613
+ default_tickers_hist = available_tickers_hist[:3] if available_tickers_hist else []
614
+
615
+ asset_selector = gr.Dropdown(choices=available_tickers_hist, value=default_tickers_hist, multiselect=True, label="1. Select Assets")
616
+ period_selector = gr.Dropdown(choices=list(TIME_PERIODS.keys()), value="1 Year", label="2. Select Period")
617
+ analyze_btn = gr.Button("๐Ÿ”Ž Run Analysis", variant="primary")
618
+
619
  with gr.Column(scale=3):
620
+ historical_plot = gr.Plot(label="Performance Plot")
621
+
622
+ gr.Markdown("---")
623
+ historical_analysis_md = gr.Markdown("### ๐Ÿค– AI Analyst Report\n\n*Click 'Run Analysis' to generate.*")
624
+
625
+ analyze_btn.click(
626
+ fn=run_historical_analysis,
627
+ inputs=[asset_selector, period_selector],
628
+ outputs=[historical_plot, historical_analysis_md]
629
+ )
630
+
631
+ # ================= TAB 4: HISTORICAL SIMULATION (UPDATED with Pro Metrics) =================
632
+ with gr.TabItem("๐Ÿ”™ Historical Simulation"):
633
+ gr.Markdown("### Backtest the RL Agent against Baselines")
634
+
635
+ # Disclaimer Box
636
+ gr.HTML(f"""
637
+ <div class='disclaimer-box'>
638
+ <strong>โš ๏ธ IMPORTANT DISCLAIMER:</strong> The RL model was trained on data from approximately
639
+ <strong>{TRAIN_START_DATE} to {TRAIN_END_DATE}</strong>. Running simulations outside or overlapping significantly
640
+ with this period may not accurately reflect real-world performance (lookahead bias or out-of-distribution data).
641
+ Use for educational purposes only.
642
+ </div>
643
+ """)
644
 
 
645
  with gr.Row():
646
+ with gr.Column(scale=1):
647
+ start_date_input = gr.Textbox(label="Start Date (YYYY-MM-DD)", value=(datetime.now() - timedelta(days=365)).strftime('%Y-%m-%d'))
648
+ end_date_input = gr.Textbox(label="End Date (YYYY-MM-DD)", value=(datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d'))
649
+ sim_btn = gr.Button("โ–ถ๏ธ Run Simulation", variant="primary")
650
+ sim_status = gr.Textbox(label="Status", interactive=False, lines=1)
651
+
652
+ with gr.Column(scale=3):
653
+ sim_plot = gr.Plot(label="Simulation Performance")
654
+
655
+ gr.Markdown("---")
656
+ # Updated to Markdown component for better table formatting
657
+ sim_metrics_md = gr.Markdown("### ๐Ÿ“Š Professional Performance Metrics\n\n*Run simulation to see metrics.*")
658
+
659
+ sim_btn.click(
660
+ fn=run_historical_simulation,
661
+ inputs=[start_date_input, end_date_input],
662
+ outputs=[sim_plot, sim_status, sim_metrics_md]
663
+ )
664
 
665
  if __name__ == "__main__":
666
  demo.queue().launch(server_name="0.0.0.0", server_port=7860, debug=True, share=True)