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
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
"""
2D PDF visualization components.

Create single and comparison plots for probability density functions.
"""

import numpy as np
import plotly.graph_objects as go
from typing import Dict, List, Optional, Tuple
from src.visualization.themes import (
    create_base_layout,
    get_line_style,
    format_hover_template,
    DARK_THEME
)


def plot_pdf_2d(
    strikes: np.ndarray,
    pdf: np.ndarray,
    spot_price: float,
    title: str = "Option-Implied Probability Density",
    show_spot: bool = True,
    show_ci: bool = True,
    ci_levels: Tuple[float, float] = (0.16, 0.84)
) -> go.Figure:
    """
    Create 2D plot of probability density function.

    Args:
        strikes: Strike prices
        pdf: PDF values
        spot_price: Current spot price
        title: Plot title
        show_spot: Whether to show vertical line at spot price
        show_ci: Whether to show confidence interval shading
        ci_levels: Confidence interval levels (default: 68% CI)

    Returns:
        Plotly figure
    """
    fig = go.Figure()

    # Main PDF line
    fig.add_trace(go.Scatter(
        x=strikes,
        y=pdf,
        mode='lines',
        name='PDF',
        line=dict(
            color=DARK_THEME['primary'],
            width=3
        ),
        fill='tozeroy',
        fillcolor=f"rgba(0, 217, 255, 0.2)",  # Semi-transparent cyan
        hovertemplate=format_hover_template("Strike", "Probability Density")
    ))

    # Add spot price indicator
    if show_spot:
        fig.add_vline(
            x=spot_price,
            line_dash="dash",
            line_color=DARK_THEME['success'],
            line_width=2,
            annotation_text=f"Spot: ${spot_price:.2f}",
            annotation_position="top"
        )

    # Add confidence interval shading
    if show_ci and ci_levels:
        try:
            from scipy.integrate import cumulative_trapezoid
        except ImportError:
            from scipy.integrate import cumtrapz as cumulative_trapezoid

        # Calculate CDF
        cdf = cumulative_trapezoid(pdf, strikes, initial=0)
        cdf = cdf / cdf[-1]  # Normalize

        # Find strikes at CI levels
        lower_strike = np.interp(ci_levels[0], cdf, strikes)
        upper_strike = np.interp(ci_levels[1], cdf, strikes)

        # Add shaded region
        ci_mask = (strikes >= lower_strike) & (strikes <= upper_strike)

        fig.add_trace(go.Scatter(
            x=strikes[ci_mask],
            y=pdf[ci_mask],
            mode='lines',
            name=f'{int((ci_levels[1]-ci_levels[0])*100)}% CI',
            line=dict(width=0),
            fill='tozeroy',
            fillcolor='rgba(0, 255, 136, 0.15)',  # Semi-transparent green
            showlegend=True,
            hoverinfo='skip'
        ))

        # Add vertical lines for CI bounds
        fig.add_vline(
            x=lower_strike,
            line_dash="dot",
            line_color=DARK_THEME['neutral'],
            line_width=1,
            annotation_text=f"${lower_strike:.2f}",
            annotation_position="bottom"
        )
        fig.add_vline(
            x=upper_strike,
            line_dash="dot",
            line_color=DARK_THEME['neutral'],
            line_width=1,
            annotation_text=f"${upper_strike:.2f}",
            annotation_position="bottom"
        )

    # Layout
    layout = create_base_layout(
        title=title,
        xaxis_title="Strike Price ($)",
        yaxis_title="Probability Density",
        showlegend=True,
        legend=dict(
            x=0.02,
            y=0.98,
            bgcolor='rgba(20,20,20,0.8)',
            bordercolor=DARK_THEME['grid'],
            borderwidth=1
        )
    )

    fig.update_layout(**layout)

    return fig


def plot_pdf_comparison(
    pdf_data: Dict[str, Dict[str, np.ndarray]],
    spot_price: float,
    title: str = "PDF Comparison Across Expirations"
) -> go.Figure:
    """
    Create comparison plot of multiple PDFs.

    Args:
        pdf_data: Dictionary with format:
            {
                'expiration_date': {
                    'strikes': np.ndarray,
                    'pdf': np.ndarray,
                    'days_to_expiry': int
                }
            }
        spot_price: Current spot price
        title: Plot title

    Returns:
        Plotly figure
    """
    fig = go.Figure()

    # Sort by days to expiry
    sorted_data = sorted(
        pdf_data.items(),
        key=lambda x: x[1]['days_to_expiry']
    )

    # Add each PDF as a line
    for idx, (exp_date, data) in enumerate(sorted_data):
        strikes = data['strikes']
        pdf = data['pdf']
        days = data['days_to_expiry']

        style = get_line_style(idx)

        fig.add_trace(go.Scatter(
            x=strikes,
            y=pdf,
            mode='lines',
            name=f"{days}D ({exp_date})",
            line=style,
            hovertemplate=format_hover_template(
                "Strike",
                "Probability",
                {'Expiration': exp_date, 'DTE': f'{days} days'}
            )
        ))

    # Add spot price indicator
    fig.add_vline(
        x=spot_price,
        line_dash="dash",
        line_color=DARK_THEME['success'],
        line_width=2,
        annotation_text=f"Spot: ${spot_price:.2f}",
        annotation_position="top"
    )

    # Layout
    layout = create_base_layout(
        title=title,
        xaxis_title="Strike Price ($)",
        yaxis_title="Probability Density",
        showlegend=True,
        legend=dict(
            x=0.02,
            y=0.98,
            bgcolor='rgba(20,20,20,0.8)',
            bordercolor=DARK_THEME['grid'],
            borderwidth=1
        )
    )

    fig.update_layout(**layout)

    return fig


def plot_cdf(
    strikes: np.ndarray,
    cdf: np.ndarray,
    spot_price: float,
    title: str = "Cumulative Distribution Function",
    show_percentiles: bool = True
) -> go.Figure:
    """
    Plot cumulative distribution function.

    Args:
        strikes: Strike prices
        cdf: CDF values (0 to 1)
        spot_price: Current spot price
        title: Plot title
        show_percentiles: Whether to show key percentile lines

    Returns:
        Plotly figure
    """
    fig = go.Figure()

    # Main CDF line
    fig.add_trace(go.Scatter(
        x=strikes,
        y=cdf * 100,  # Convert to percentage
        mode='lines',
        name='CDF',
        line=dict(
            color=DARK_THEME['secondary'],
            width=3
        ),
        hovertemplate=format_hover_template("Strike", "Cumulative Probability (%)")
    ))

    # Add spot price indicator
    fig.add_vline(
        x=spot_price,
        line_dash="dash",
        line_color=DARK_THEME['success'],
        line_width=2,
        annotation_text=f"Spot: ${spot_price:.2f}",
        annotation_position="top"
    )

    # Add percentile lines
    if show_percentiles:
        percentiles = [25, 50, 75]
        for p in percentiles:
            strike_at_p = np.interp(p / 100, cdf, strikes)

            fig.add_hline(
                y=p,
                line_dash="dot",
                line_color=DARK_THEME['neutral'],
                line_width=1,
                annotation_text=f"P{p}",
                annotation_position="right"
            )

            fig.add_vline(
                x=strike_at_p,
                line_dash="dot",
                line_color=DARK_THEME['neutral'],
                line_width=1,
                annotation_text=f"${strike_at_p:.0f}",
                annotation_position="top"
            )

    # Layout
    layout = create_base_layout(
        title=title,
        xaxis_title="Strike Price ($)",
        yaxis_title="Cumulative Probability (%)",
        showlegend=False
    )

    # Set y-axis range to 0-100%
    layout['yaxis']['range'] = [0, 100]

    fig.update_layout(**layout)

    return fig


def plot_pdf_vs_normal(
    strikes: np.ndarray,
    pdf: np.ndarray,
    mean: float,
    std: float,
    spot_price: float,
    title: str = "PDF vs Normal Distribution"
) -> go.Figure:
    """
    Compare PDF to normal distribution with same mean and std.

    Args:
        strikes: Strike prices
        pdf: Actual PDF values
        mean: PDF mean
        std: PDF standard deviation
        spot_price: Current spot price
        title: Plot title

    Returns:
        Plotly figure
    """
    from scipy.stats import norm

    fig = go.Figure()

    # Actual PDF
    fig.add_trace(go.Scatter(
        x=strikes,
        y=pdf,
        mode='lines',
        name='Market PDF',
        line=dict(
            color=DARK_THEME['primary'],
            width=3
        ),
        hovertemplate=format_hover_template("Strike", "Probability Density")
    ))

    # Normal distribution
    normal_pdf = norm.pdf(strikes, loc=mean, scale=std)

    fig.add_trace(go.Scatter(
        x=strikes,
        y=normal_pdf,
        mode='lines',
        name='Normal Distribution',
        line=dict(
            color=DARK_THEME['warning'],
            width=2,
            dash='dash'
        ),
        hovertemplate=format_hover_template("Strike", "Normal PDF")
    ))

    # Add spot price indicator
    fig.add_vline(
        x=spot_price,
        line_dash="dot",
        line_color=DARK_THEME['success'],
        line_width=2,
        annotation_text=f"Spot: ${spot_price:.2f}",
        annotation_position="top"
    )

    # Layout
    layout = create_base_layout(
        title=title,
        xaxis_title="Strike Price ($)",
        yaxis_title="Probability Density",
        showlegend=True,
        legend=dict(
            x=0.02,
            y=0.98,
            bgcolor='rgba(20,20,20,0.8)',
            bordercolor=DARK_THEME['grid'],
            borderwidth=1
        )
    )

    fig.update_layout(**layout)

    return fig


if __name__ == "__main__":
    # Test 2D PDF plots
    print("Testing 2D PDF plots...")

    # Create synthetic PDF data
    spot = 450.0
    strikes = np.linspace(400, 500, 200)
    mean = spot
    std = 15

    # Lognormal-like PDF
    from scipy.stats import norm
    pdf = norm.pdf(strikes, loc=mean, scale=std)

    # Test single PDF plot
    fig1 = plot_pdf_2d(strikes, pdf, spot)
    fig1.write_html("test_pdf_2d.html")
    print("✅ 2D PDF plot saved to test_pdf_2d.html")

    # Test CDF plot
    try:
        from scipy.integrate import cumulative_trapezoid
    except ImportError:
        from scipy.integrate import cumtrapz as cumulative_trapezoid
    cdf = cumulative_trapezoid(pdf, strikes, initial=0)
    cdf = cdf / cdf[-1]

    fig2 = plot_cdf(strikes, cdf, spot)
    fig2.write_html("test_cdf.html")
    print("✅ CDF plot saved to test_cdf.html")

    # Test comparison plot
    pdf_data = {
        '2025-01-15': {
            'strikes': strikes,
            'pdf': norm.pdf(strikes, mean, std * 0.8),
            'days_to_expiry': 15
        },
        '2025-02-01': {
            'strikes': strikes,
            'pdf': norm.pdf(strikes, mean, std),
            'days_to_expiry': 30
        },
        '2025-03-01': {
            'strikes': strikes,
            'pdf': norm.pdf(strikes, mean, std * 1.2),
            'days_to_expiry': 60
        }
    }

    fig3 = plot_pdf_comparison(pdf_data, spot)
    fig3.write_html("test_pdf_comparison.html")
    print("✅ PDF comparison saved to test_pdf_comparison.html")

    # Test PDF vs Normal
    fig4 = plot_pdf_vs_normal(strikes, pdf, mean, std, spot)
    fig4.write_html("test_pdf_vs_normal.html")
    print("✅ PDF vs Normal saved to test_pdf_vs_normal.html")

    print("\n✅ All 2D PDF visualization tests passed!")