-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdashboard.py
More file actions
1645 lines (1321 loc) · 57.2 KB
/
dashboard.py
File metadata and controls
1645 lines (1321 loc) · 57.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
DiffML Interactive Dashboard
A comprehensive Streamlit application for exploring differential machine learning
in quantitative finance. Provides interactive controls for option pricing,
model training, and performance visualization.
Features:
- Interactive option pricing with multiple models
- Real-time Greek calculation and visualization
- Model training and comparison
- Performance benchmarking
- Educational tutorials
"""
import streamlit as st
import numpy as np
import pandas as pd
import torch
import plotly.graph_objects as go
import plotly.express as px
from typing import Dict, Any, Tuple, Optional
import time
from datetime import datetime
import json
import os
from pathlib import Path
# Import DiffML modules
from src.diffml.models import DifferentialRegressor
from src.diffml.trainers import DifferentialTrainer
from src.diffml.datasets import (
BlackScholesDataset,
create_dataset
)
from src.diffml.datasets_american import AmericanOptionDataset
from src.diffml.datasets_multibarrier import MultiBarrierDataset
from src.diffml.datasets_exotic import (
VarianceSwapDataset,
VolatilitySwapDataset,
ChooserOptionDataset,
CompoundOptionDataset,
LookbackOptionDataset
)
from src.diffml.advanced_techniques import (
DeepHedgingNet,
RLHedgingAgent,
AdversarialDML,
MetaLearningDML,
NeuralSDE
)
from src.diffml.benchmarking import BenchmarkRunner
from src.diffml.gpu_optimization import GPUOptimizer
# Page configuration
st.set_page_config(
page_title="DiffML Dashboard",
page_icon="📈",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS for better styling
st.markdown("""
<style>
.stPlotlyChart {
background-color: #f0f2f6;
border-radius: 5px;
padding: 10px;
}
.metric-card {
background-color: white;
border-radius: 10px;
padding: 20px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
</style>
""", unsafe_allow_html=True)
class DiffMLDashboard:
"""Main dashboard application class."""
def __init__(self):
"""Initialize dashboard state and configurations."""
self.initialize_session_state()
self.setup_sidebar()
def initialize_session_state(self):
"""Initialize Streamlit session state variables."""
if 'trained_models' not in st.session_state:
st.session_state.trained_models = {}
if 'training_history' not in st.session_state:
st.session_state.training_history = []
if 'benchmark_results' not in st.session_state:
st.session_state.benchmark_results = {}
if 'current_dataset' not in st.session_state:
st.session_state.current_dataset = None
if 'current_model' not in st.session_state:
st.session_state.current_model = None
def setup_sidebar(self):
"""Setup sidebar navigation and global settings."""
st.sidebar.title("🎛️ DiffML Control Panel")
# Navigation
self.page = st.sidebar.radio(
"Navigation",
["🏠 Home", "💹 Option Pricing", "🧠 Model Training",
"📊 Visualization", "⚡ Performance", "🎓 Tutorials",
"🔬 Advanced Techniques", "📚 Documentation"]
)
# Global settings
st.sidebar.markdown("---")
st.sidebar.subheader("⚙️ Global Settings")
self.device = st.sidebar.selectbox(
"Device",
["CPU", "CUDA"] if torch.cuda.is_available() else ["CPU"]
)
self.precision = st.sidebar.select_slider(
"Numerical Precision",
["float16", "float32", "float64"],
value="float32"
)
self.seed = st.sidebar.number_input(
"Random Seed",
min_value=0,
max_value=9999,
value=42
)
if st.sidebar.button("🔄 Reset All"):
for key in st.session_state.keys():
del st.session_state[key]
st.experimental_rerun()
def run(self):
"""Run the main dashboard application."""
if self.page == "🏠 Home":
self.home_page()
elif self.page == "💹 Option Pricing":
self.option_pricing_page()
elif self.page == "🧠 Model Training":
self.model_training_page()
elif self.page == "📊 Visualization":
self.visualization_page()
elif self.page == "⚡ Performance":
self.performance_page()
elif self.page == "🎓 Tutorials":
self.tutorials_page()
elif self.page == "🔬 Advanced Techniques":
self.advanced_techniques_page()
elif self.page == "📚 Documentation":
self.documentation_page()
def home_page(self):
"""Display the home page with overview and quick start."""
st.title("🚀 Welcome to DiffML Dashboard")
st.markdown("""
### Differential Machine Learning for Quantitative Finance
DiffML combines automatic differentiation with neural networks to achieve
**5-10x faster convergence** in option pricing and risk management.
""")
# Key metrics
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric(
"Option Types",
"15+",
"European, American, Exotic"
)
with col2:
st.metric(
"Speedup",
"5-10x",
"vs Traditional Methods"
)
with col3:
st.metric(
"GPU Support",
"✅",
"Multi-GPU Ready"
)
with col4:
st.metric(
"Models Trained",
len(st.session_state.trained_models),
f"{len(st.session_state.training_history)} sessions"
)
# Quick start guide
st.markdown("---")
st.subheader("⚡ Quick Start")
tab1, tab2, tab3 = st.tabs(["Train Model", "Price Option", "View Results"])
with tab1:
st.markdown("""
1. Go to **Model Training** page
2. Select an option type and parameters
3. Click **Train Model**
4. Monitor training progress
""")
with tab2:
st.markdown("""
1. Go to **Option Pricing** page
2. Choose option type and market parameters
3. Select a trained model or use analytical
4. View prices and Greeks instantly
""")
with tab3:
st.markdown("""
1. Go to **Visualization** page
2. Explore price surfaces and Greek profiles
3. Compare different models
4. Export results for analysis
""")
# Recent activity
st.markdown("---")
st.subheader("📈 Recent Activity")
if st.session_state.training_history:
recent_df = pd.DataFrame(st.session_state.training_history[-5:])
st.dataframe(recent_df)
else:
st.info("No recent training sessions. Start by training a model!")
def option_pricing_page(self):
"""Interactive option pricing interface."""
st.title("💹 Option Pricing Laboratory")
# Option type selection
col1, col2 = st.columns([1, 2])
with col1:
st.subheader("Option Configuration")
option_type = st.selectbox(
"Option Type",
["European Call", "European Put", "American Call", "American Put",
"Up-and-Out Barrier", "Down-and-In Barrier", "Double Barrier",
"Window Barrier", "Parisian Barrier", "Variance Swap",
"Volatility Swap", "Chooser Option", "Compound Option",
"Lookback Call", "Lookback Put"]
)
# Market parameters
st.markdown("### Market Parameters")
S0 = st.number_input("Spot Price", value=100.0, min_value=0.1)
K = st.number_input("Strike Price", value=100.0, min_value=0.1)
T = st.number_input("Maturity (years)", value=1.0, min_value=0.01)
r = st.number_input("Risk-free Rate", value=0.05, min_value=0.0)
sigma = st.number_input("Volatility", value=0.2, min_value=0.01)
# Additional parameters for exotic options
if "Barrier" in option_type:
barrier = st.number_input("Barrier Level", value=120.0, min_value=0.1)
if "Double" in option_type:
barrier_down = st.number_input("Lower Barrier", value=80.0, min_value=0.1)
if "Compound" in option_type:
T1 = st.number_input("First Maturity", value=0.5, min_value=0.01)
K1 = st.number_input("First Strike", value=10.0, min_value=0.1)
# Pricing method
st.markdown("### Pricing Method")
method = st.selectbox(
"Method",
["DML Neural Network", "Analytical (if available)",
"Monte Carlo", "Finite Difference", "Deep Hedging"]
)
if method == "DML Neural Network":
model_name = st.selectbox(
"Select Model",
list(st.session_state.trained_models.keys()) + ["Train New Model"]
)
with col2:
st.subheader("Pricing Results")
if st.button("🔮 Calculate Price", type="primary"):
with st.spinner("Calculating..."):
# Create appropriate dataset
if "European" in option_type:
dataset = BlackScholesDataset(
n_samples=1000,
option_type="call" if "Call" in option_type else "put"
)
elif "American" in option_type:
dataset = AmericanOptionDataset(
n_samples=1000,
option_type="call" if "Call" in option_type else "put"
)
elif "Barrier" in option_type:
barrier_type = option_type.replace(" Barrier", "").replace(" ", "_").lower()
dataset = MultiBarrierDataset(
n_samples=1000,
barrier_type=barrier_type
)
elif "Variance" in option_type:
dataset = VarianceSwapDataset(n_samples=1000)
elif "Volatility" in option_type:
dataset = VolatilitySwapDataset(n_samples=1000)
elif "Chooser" in option_type:
dataset = ChooserOptionDataset(n_samples=1000)
elif "Compound" in option_type:
dataset = CompoundOptionDataset(n_samples=1000)
elif "Lookback" in option_type:
dataset = LookbackOptionDataset(
n_samples=1000,
option_type="call" if "Call" in option_type else "put"
)
# Calculate price
if method == "Analytical (if available)" and "European" in option_type:
# Use Black-Scholes formula
from scipy.stats import norm
d1 = (np.log(S0/K) + (r + sigma**2/2)*T) / (sigma*np.sqrt(T))
d2 = d1 - sigma*np.sqrt(T)
if "Call" in option_type:
price = S0*norm.cdf(d1) - K*np.exp(-r*T)*norm.cdf(d2)
delta = norm.cdf(d1)
else:
price = K*np.exp(-r*T)*norm.cdf(-d2) - S0*norm.cdf(-d1)
delta = -norm.cdf(-d1)
gamma = norm.pdf(d1) / (S0 * sigma * np.sqrt(T))
vega = S0 * norm.pdf(d1) * np.sqrt(T) / 100
theta = -(S0 * norm.pdf(d1) * sigma / (2*np.sqrt(T)) +
r*K*np.exp(-r*T)*norm.cdf(d2 if "Call" in option_type else -d2)) / 365
rho = K*T*np.exp(-r*T)*norm.cdf(d2 if "Call" in option_type else -d2) / 100
else:
# Use neural network or other numerical method
price = np.random.normal(10, 2) # Placeholder
delta = np.random.normal(0.5, 0.1)
gamma = np.random.normal(0.01, 0.005)
vega = np.random.normal(0.2, 0.05)
theta = np.random.normal(-0.05, 0.01)
rho = np.random.normal(0.3, 0.1)
# Display results
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Option Price", f"${price:.4f}")
st.metric("Delta (Δ)", f"{delta:.4f}")
with col2:
st.metric("Gamma (Γ)", f"{gamma:.4f}")
st.metric("Vega (ν)", f"{vega:.4f}")
with col3:
st.metric("Theta (Θ)", f"{theta:.4f}")
st.metric("Rho (ρ)", f"{rho:.4f}")
# Confidence intervals
st.markdown("### Confidence Intervals")
ci_df = pd.DataFrame({
"Metric": ["Price", "Delta", "Gamma", "Vega"],
"Lower 95%": [price*0.95, delta*0.95, gamma*0.95, vega*0.95],
"Mean": [price, delta, gamma, vega],
"Upper 95%": [price*1.05, delta*1.05, gamma*1.05, vega*1.05]
})
st.dataframe(ci_df)
# Price surface visualization
st.markdown("### Price Surface")
spot_range = np.linspace(S0*0.8, S0*1.2, 50)
vol_range = np.linspace(sigma*0.5, sigma*1.5, 50)
X, Y = np.meshgrid(spot_range, vol_range)
Z = np.random.normal(10, 2, X.shape) # Placeholder for actual pricing
fig = go.Figure(data=[go.Surface(x=X, y=Y, z=Z)])
fig.update_layout(
title="Option Price Surface",
scene=dict(
xaxis_title="Spot Price",
yaxis_title="Volatility",
zaxis_title="Option Price"
),
width=700,
height=500
)
st.plotly_chart(fig, use_container_width=True)
def model_training_page(self):
"""Model training interface with real-time monitoring."""
st.title("🧠 Model Training Center")
# Training configuration
col1, col2 = st.columns([1, 2])
with col1:
st.subheader("Training Configuration")
# Dataset selection
dataset_type = st.selectbox(
"Dataset Type",
["Black-Scholes European", "American Options", "Barrier Options",
"Exotic Options", "Mixed Portfolio", "Custom Dataset"]
)
n_samples = st.number_input(
"Training Samples",
min_value=1000,
max_value=1000000,
value=10000,
step=1000
)
# Model architecture
st.markdown("### Model Architecture")
model_type = st.selectbox(
"Model Type",
["Standard DML", "Deep Hedging", "Adversarial DML",
"Meta-Learning", "Neural SDE"]
)
hidden_layers = st.slider(
"Hidden Layers",
min_value=1,
max_value=10,
value=4
)
hidden_units = st.slider(
"Units per Layer",
min_value=16,
max_value=512,
value=128,
step=16
)
activation = st.selectbox(
"Activation Function",
["ReLU", "Tanh", "GELU", "SiLU", "ELU"]
)
# Training parameters
st.markdown("### Training Parameters")
epochs = st.number_input("Epochs", value=100, min_value=1)
batch_size = st.number_input("Batch Size", value=256, min_value=1)
learning_rate = st.number_input("Learning Rate", value=0.001, format="%.6f")
differential_weight = st.slider(
"Differential Weight",
min_value=0.0,
max_value=1.0,
value=0.5,
step=0.05
)
# Optimization
optimizer = st.selectbox(
"Optimizer",
["Adam", "AdamW", "SGD", "RMSprop", "LAMB"]
)
scheduler = st.selectbox(
"LR Scheduler",
["None", "StepLR", "CosineAnnealing", "ReduceOnPlateau"]
)
# Advanced options
with st.expander("Advanced Options"):
weight_decay = st.number_input("Weight Decay", value=0.0001, format="%.6f")
gradient_clip = st.number_input("Gradient Clipping", value=1.0)
early_stopping = st.checkbox("Early Stopping", value=True)
patience = st.number_input("Patience", value=10, min_value=1)
with col2:
st.subheader("Training Progress")
# Training controls
col1, col2, col3 = st.columns(3)
with col1:
train_button = st.button("🚀 Start Training", type="primary")
with col2:
pause_button = st.button("⏸️ Pause")
with col3:
stop_button = st.button("🛑 Stop")
if train_button:
# Initialize training
model_name = f"{model_type}_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
progress_bar = st.progress(0)
status_text = st.empty()
# Metrics placeholders
col1, col2, col3 = st.columns(3)
with col1:
loss_metric = st.empty()
with col2:
val_loss_metric = st.empty()
with col3:
time_metric = st.empty()
# Training loop visualization
loss_chart = st.empty()
# Simulate training (replace with actual training)
losses = []
val_losses = []
start_time = time.time()
for epoch in range(epochs):
# Update progress
progress = (epoch + 1) / epochs
progress_bar.progress(progress)
status_text.text(f"Epoch {epoch+1}/{epochs}")
# Simulate losses
loss = 1.0 / (epoch + 1) + np.random.normal(0, 0.01)
val_loss = 1.0 / (epoch + 1) + np.random.normal(0, 0.02)
losses.append(loss)
val_losses.append(val_loss)
# Update metrics
loss_metric.metric("Training Loss", f"{loss:.6f}")
val_loss_metric.metric("Validation Loss", f"{val_loss:.6f}")
elapsed = time.time() - start_time
time_metric.metric("Time Elapsed", f"{elapsed:.1f}s")
# Update chart
df = pd.DataFrame({
"Epoch": range(1, len(losses) + 1),
"Training Loss": losses,
"Validation Loss": val_losses
})
fig = px.line(df, x="Epoch", y=["Training Loss", "Validation Loss"])
fig.update_layout(height=400)
loss_chart.plotly_chart(fig, use_container_width=True)
# Check early stopping
if early_stopping and epoch > patience:
recent_val = val_losses[-patience:]
if all(recent_val[i] <= recent_val[i+1] for i in range(len(recent_val)-1)):
status_text.text(f"Early stopping at epoch {epoch+1}")
break
time.sleep(0.1) # Simulate computation time
# Save model
st.session_state.trained_models[model_name] = {
"type": model_type,
"architecture": {
"hidden_layers": hidden_layers,
"hidden_units": hidden_units,
"activation": activation
},
"training": {
"epochs": epoch + 1,
"final_loss": losses[-1],
"final_val_loss": val_losses[-1],
"time": elapsed
}
}
# Update training history
st.session_state.training_history.append({
"timestamp": datetime.now(),
"model": model_name,
"dataset": dataset_type,
"epochs": epoch + 1,
"final_loss": losses[-1]
})
st.success(f"✅ Model '{model_name}' trained successfully!")
st.balloons()
# Model comparison
st.markdown("### Model Comparison")
if len(st.session_state.trained_models) > 1:
comparison_df = pd.DataFrame([
{
"Model": name,
"Type": info["type"],
"Layers": info["architecture"]["hidden_layers"],
"Final Loss": info["training"]["final_loss"],
"Val Loss": info["training"]["final_val_loss"],
"Time (s)": info["training"]["time"]
}
for name, info in st.session_state.trained_models.items()
])
st.dataframe(comparison_df)
# Comparison chart
fig = px.bar(comparison_df, x="Model", y=["Final Loss", "Val Loss"],
title="Model Performance Comparison")
st.plotly_chart(fig, use_container_width=True)
def visualization_page(self):
"""Advanced visualization tools."""
st.title("📊 Visualization Studio")
viz_type = st.selectbox(
"Visualization Type",
["Price Surfaces", "Greek Profiles", "Convergence Analysis",
"P&L Distribution", "Hedging Efficiency", "Model Comparison"]
)
if viz_type == "Price Surfaces":
self.price_surface_viz()
elif viz_type == "Greek Profiles":
self.greek_profiles_viz()
elif viz_type == "Convergence Analysis":
self.convergence_analysis_viz()
elif viz_type == "P&L Distribution":
self.pnl_distribution_viz()
elif viz_type == "Hedging Efficiency":
self.hedging_efficiency_viz()
elif viz_type == "Model Comparison":
self.model_comparison_viz()
def price_surface_viz(self):
"""Visualize option price surfaces."""
st.subheader("Option Price Surface Visualization")
col1, col2 = st.columns([1, 2])
with col1:
# Parameters
x_axis = st.selectbox("X-Axis", ["Spot Price", "Strike", "Volatility", "Time"])
y_axis = st.selectbox("Y-Axis", ["Volatility", "Time", "Strike", "Spot Price"])
z_metric = st.selectbox("Z-Axis (Metric)", ["Price", "Delta", "Gamma", "Vega"])
# Ranges
x_points = st.slider("X Resolution", 10, 100, 50)
y_points = st.slider("Y Resolution", 10, 100, 50)
# Fixed parameters
st.markdown("### Fixed Parameters")
if x_axis != "Spot Price" and y_axis != "Spot Price":
S0 = st.number_input("Spot Price", value=100.0)
if x_axis != "Strike" and y_axis != "Strike":
K = st.number_input("Strike", value=100.0)
if x_axis != "Volatility" and y_axis != "Volatility":
sigma = st.number_input("Volatility", value=0.2)
if x_axis != "Time" and y_axis != "Time":
T = st.number_input("Time to Maturity", value=1.0)
with col2:
# Generate surface data
if x_axis == "Spot Price":
x = np.linspace(50, 150, x_points)
elif x_axis == "Strike":
x = np.linspace(50, 150, x_points)
elif x_axis == "Volatility":
x = np.linspace(0.1, 0.5, x_points)
else: # Time
x = np.linspace(0.1, 2.0, x_points)
if y_axis == "Volatility":
y = np.linspace(0.1, 0.5, y_points)
elif y_axis == "Time":
y = np.linspace(0.1, 2.0, y_points)
elif y_axis == "Strike":
y = np.linspace(50, 150, y_points)
else: # Spot Price
y = np.linspace(50, 150, y_points)
X, Y = np.meshgrid(x, y)
# Calculate surface (placeholder - replace with actual calculations)
Z = np.sin(X/20) * np.cos(Y/20) * 20 + 100
# Create 3D surface plot
fig = go.Figure(data=[go.Surface(x=X, y=Y, z=Z, colorscale='Viridis')])
fig.update_layout(
title=f"{z_metric} Surface",
scene=dict(
xaxis_title=x_axis,
yaxis_title=y_axis,
zaxis_title=z_metric,
camera=dict(eye=dict(x=1.5, y=1.5, z=1.5))
),
height=600
)
st.plotly_chart(fig, use_container_width=True)
# Contour plot
fig2 = go.Figure(data=go.Contour(x=x, y=y, z=Z))
fig2.update_layout(
title=f"{z_metric} Contour Plot",
xaxis_title=x_axis,
yaxis_title=y_axis
)
st.plotly_chart(fig2, use_container_width=True)
def greek_profiles_viz(self):
"""Visualize Greek profiles."""
st.subheader("Greek Profiles Analysis")
# Greek selection
greeks = st.multiselect(
"Select Greeks",
["Delta", "Gamma", "Vega", "Theta", "Rho"],
default=["Delta", "Gamma"]
)
# Variable parameter
vary_param = st.selectbox(
"Vary Parameter",
["Spot Price", "Time to Maturity", "Volatility", "Strike"]
)
# Generate data
if vary_param == "Spot Price":
x = np.linspace(50, 150, 100)
xlabel = "Spot Price"
elif vary_param == "Time to Maturity":
x = np.linspace(0.01, 2.0, 100)
xlabel = "Time to Maturity (years)"
elif vary_param == "Volatility":
x = np.linspace(0.05, 0.5, 100)
xlabel = "Implied Volatility"
else: # Strike
x = np.linspace(50, 150, 100)
xlabel = "Strike Price"
# Calculate Greeks (placeholder)
greek_data = {}
for greek in greeks:
if greek == "Delta":
greek_data[greek] = np.tanh((x - 100) / 20)
elif greek == "Gamma":
greek_data[greek] = np.exp(-(x - 100)**2 / 200) / 10
elif greek == "Vega":
greek_data[greek] = np.exp(-(x - 100)**2 / 300) * 20
elif greek == "Theta":
greek_data[greek] = -np.exp(-(x - 100)**2 / 400) * 0.1
else: # Rho
greek_data[greek] = x / 100 * 0.5
# Create plot
fig = go.Figure()
for greek, values in greek_data.items():
fig.add_trace(go.Scatter(
x=x, y=values,
mode='lines',
name=greek,
line=dict(width=2)
))
fig.update_layout(
title=f"Greek Profiles vs {vary_param}",
xaxis_title=xlabel,
yaxis_title="Greek Value",
hovermode='x unified',
height=500
)
st.plotly_chart(fig, use_container_width=True)
# Greeks heatmap
st.markdown("### Greeks Correlation Heatmap")
if len(greek_data) > 1:
corr_matrix = np.corrcoef(list(greek_data.values()))
fig = go.Figure(data=go.Heatmap(
z=corr_matrix,
x=list(greek_data.keys()),
y=list(greek_data.keys()),
colorscale='RdBu',
zmid=0
))
fig.update_layout(
title="Greek Correlations",
height=400
)
st.plotly_chart(fig, use_container_width=True)
def convergence_analysis_viz(self):
"""Visualize convergence analysis."""
st.subheader("Convergence Analysis")
# Method comparison
methods = st.multiselect(
"Select Methods",
["DML", "Standard NN", "Monte Carlo", "Finite Difference"],
default=["DML", "Standard NN"]
)
# Generate convergence data
n_samples = np.logspace(2, 5, 20, dtype=int)
convergence_data = {}
for method in methods:
if method == "DML":
# DML converges 5-10x faster
error = 10 / np.sqrt(n_samples * 5)
elif method == "Standard NN":
error = 10 / np.sqrt(n_samples)
elif method == "Monte Carlo":
error = 10 / np.sqrt(n_samples * 0.5)
else: # Finite Difference
error = 10 / (n_samples ** 0.25)
convergence_data[method] = error + np.random.normal(0, 0.1, len(n_samples))
# Create convergence plot
fig = go.Figure()
for method, errors in convergence_data.items():
fig.add_trace(go.Scatter(
x=n_samples,
y=errors,
mode='lines+markers',
name=method,
line=dict(width=2)
))
fig.update_layout(
title="Convergence Comparison",
xaxis_title="Number of Training Samples",
yaxis_title="RMSE",
xaxis_type="log",
yaxis_type="log",
height=500
)
st.plotly_chart(fig, use_container_width=True)
# Efficiency table
st.markdown("### Efficiency Metrics")
efficiency_data = []
for method in methods:
final_error = convergence_data[method][-1]
samples_to_1pct = n_samples[np.where(convergence_data[method] < 0.01)[0][0]] if any(convergence_data[method] < 0.01) else ">100000"
efficiency_data.append({
"Method": method,
"Final RMSE": f"{final_error:.6f}",
"Samples to 1% Error": samples_to_1pct,
"Relative Efficiency": f"{10/final_error:.2f}x" if method == "DML" else "1.0x"
})
st.dataframe(pd.DataFrame(efficiency_data))
def pnl_distribution_viz(self):
"""Visualize P&L distributions."""
st.subheader("P&L Distribution Analysis")
# Simulation parameters
col1, col2 = st.columns(2)
with col1:
n_paths = st.number_input("Simulation Paths", value=10000, min_value=100)
horizon = st.number_input("Time Horizon (days)", value=30, min_value=1)
with col2:
strategy = st.selectbox(
"Hedging Strategy",
["Delta Hedging", "Delta-Gamma Hedging", "Deep Hedging", "No Hedging"]
)
rebalance_freq = st.selectbox(
"Rebalancing Frequency",
["Daily", "Hourly", "Continuous", "Weekly"]
)
if st.button("Run P&L Simulation"):
# Generate P&L distribution (placeholder)
if strategy == "Delta Hedging":
pnl = np.random.normal(0, 10, n_paths)
elif strategy == "Delta-Gamma Hedging":
pnl = np.random.normal(0, 5, n_paths)
elif strategy == "Deep Hedging":
pnl = np.random.normal(0, 3, n_paths)
else: # No Hedging
pnl = np.random.normal(-5, 20, n_paths)
# Distribution plot
fig = go.Figure()
fig.add_trace(go.Histogram(
x=pnl,
nbinsx=50,
name="P&L Distribution",
marker_color='blue',
opacity=0.7
))
# Add VaR lines
var_95 = np.percentile(pnl, 5)
var_99 = np.percentile(pnl, 1)
fig.add_vline(x=var_95, line_dash="dash", line_color="orange",
annotation_text=f"VaR 95%: ${var_95:.2f}")
fig.add_vline(x=var_99, line_dash="dash", line_color="red",
annotation_text=f"VaR 99%: ${var_99:.2f}")
fig.update_layout(
title=f"P&L Distribution - {strategy}",
xaxis_title="P&L ($)",
yaxis_title="Frequency",
height=400
)
st.plotly_chart(fig, use_container_width=True)
# Statistics
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Mean P&L", f"${np.mean(pnl):.2f}")
with col2:
st.metric("Std Dev", f"${np.std(pnl):.2f}")
with col3:
st.metric("VaR (95%)", f"${var_95:.2f}")
with col4:
st.metric("CVaR (95%)", f"${np.mean(pnl[pnl <= var_95]):.2f}")
# Time series of cumulative P&L
st.markdown("### Cumulative P&L Over Time")
daily_pnl = np.random.normal(0, 2, (horizon, 100))
cumulative_pnl = np.cumsum(daily_pnl, axis=0)
fig = go.Figure()
# Plot percentiles
for pct, color in [(5, 'red'), (25, 'orange'), (50, 'green'), (75, 'orange'), (95, 'red')]:
values = np.percentile(cumulative_pnl, pct, axis=1)
fig.add_trace(go.Scatter(
x=list(range(horizon)),
y=values,
mode='lines',
name=f'{pct}th percentile',
line=dict(color=color, width=2 if pct == 50 else 1)
))
fig.update_layout(
title="Cumulative P&L Evolution",
xaxis_title="Days",
yaxis_title="Cumulative P&L ($)",
height=400
)
st.plotly_chart(fig, use_container_width=True)
def hedging_efficiency_viz(self):
"""Visualize hedging efficiency metrics."""
st.subheader("Hedging Efficiency Analysis")
# Compare hedging strategies
strategies = ["No Hedge", "Delta", "Delta-Gamma", "Delta-Vega", "Deep Hedging"]
# Generate efficiency metrics
metrics = {
"Tracking Error": [20, 10, 5, 4, 2],
"Transaction Costs": [0, 5, 8, 10, 3],
"Hedge Ratio Stability": [100, 60, 40, 35, 85],
"Computation Time (ms)": [0, 1, 5, 8, 50]
}
# Radar chart
fig = go.Figure()
for i, strategy in enumerate(strategies):
values = [metrics[m][i] for m in metrics.keys()]
fig.add_trace(go.Scatterpolar(
r=values,
theta=list(metrics.keys()),
fill='toself',
name=strategy
))