File size: 11,758 Bytes
7bb0af0
 
 
 
dc80ba0
 
7bb0af0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e60df7c
7bb0af0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e60df7c
 
7bb0af0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e60df7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7bb0af0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e60df7c
 
 
 
 
dc80ba0
 
 
 
7bb0af0
 
 
 
 
 
 
 
dc80ba0
 
7bb0af0
e60df7c
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
"""
app.py -- Gradio UI for Value at Risk Analysis.
"""

import os

import pandas as pd
import gradio as gr
from src.logger import logger
from src.config import TICKERS, LOOKBACK_DAYS, STRESS_START_DATE, STRESS_END_DATE, STRESS_LABEL
from src.historical import historical_var_es_pipeline
from src.parametric import parametric_var_es_pipeline


def calculate_var_analysis(
    ticker: str,
    end_date_str: str,
    portfolio_value: float,
    n_days: int,
    var_confidence_label: str,
    es_confidence_label: str,
    method: str,
):
    """Calculate Value at Risk analysis based on Gradio inputs and delegate to the analysis pipeline."""
    logger.debug(
        f"Analysis requested: {ticker} | VaR={var_confidence_label} ES={es_confidence_label} | {method} | N={n_days} | Date={end_date_str} | PV=${portfolio_value:,.0f}"
    )

    var_confidence = float(var_confidence_label.strip().replace("%", "")) / 100.0
    es_confidence = float(es_confidence_label.strip().replace("%", "")) / 100.0
    var_conf_pct = var_confidence_label.strip()
    es_conf_pct = es_confidence_label.strip()

    today = pd.Timestamp.today().normalize()

    try:
        end_date = pd.to_datetime(end_date_str, errors="raise").normalize()
    except Exception:
        gr.Warning("Invalid date selection. Please try again.")
        return reset_analysis_results(n_days, var_confidence_label, es_confidence_label, method)

    if end_date >= today:
        gr.Warning(
            "Invalid date selection. VaR estimation requires historical data, so please choose a date prior to today."
        )
        return reset_analysis_results(n_days, var_confidence_label, es_confidence_label, method)

    fy_start = pd.Timestamp(year=today.year - 1, month=4, day=1)

    if end_date < fy_start:
        gr.Warning(f"VaR Date must be after {fy_start.strftime('%Y-%m-%d')}")
        return reset_analysis_results(n_days, var_confidence_label, es_confidence_label, method)

    if portfolio_value <= 0:
        gr.Warning("Portfolio value must be positive.")
        return reset_analysis_results(n_days, var_confidence_label, es_confidence_label, method)

    pipeline = historical_var_es_pipeline if method == "Historical VaR" else parametric_var_es_pipeline
    result = pipeline(
        ticker,
        var_confidence,
        es_confidence,
        LOOKBACK_DAYS,
        int(n_days),
        portfolio_value,
        end_date,
        stress_start=STRESS_START_DATE,
        stress_end=STRESS_END_DATE,
        stress_label=STRESS_LABEL,
    )

    logger.info(
        f"Analysis complete: {ticker} | VaR=${result['var_nd']:,.2f} | ES=${result['es_nd']:,.2f}"
    )

    return (
        gr.update(
            label=f"{int(n_days)}-day {var_conf_pct} VaR",
            value=f"${result['var_nd']:,.2f}",
        ),
        gr.update(
            label=f"{int(n_days)}-day {es_conf_pct} ES",
            value=f"${result['es_nd']:,.2f}",
        ),
        gr.update(
            label=f"{int(n_days)}-day {var_conf_pct} Stressed VaR",
            value=f"${result['stressed_var_nd']:,.2f}",
        ),
        gr.update(
            label=f"{int(n_days)}-day {es_conf_pct} Stressed ES",
            value=f"${result['stressed_es_nd']:,.2f}",
        ),
        gr.update(value=result["fig_dist"], visible=True),
        gr.update(value=result["excel_path"], visible=True),
    )


def reset_analysis_results(n_days: float, var_confidence_label: str, es_confidence_label: str, method: str):
    """Reset and hide analysis results when input parameters are modified."""
    var_conf_pct = var_confidence_label.strip()
    es_conf_pct = es_confidence_label.strip()
    method_short = "Historical" if method == "Historical VaR" else "Parametric"

    return (
        gr.update(value="", label=f"{int(n_days)}-day {var_conf_pct} VaR"),
        gr.update(value="", label=f"{int(n_days)}-day {es_conf_pct} ES"),
        gr.update(value="", label=f"{int(n_days)}-day {var_conf_pct} Stressed VaR"),
        gr.update(value="", label=f"{int(n_days)}-day {es_conf_pct} Stressed ES"),
        gr.update(value=None, visible=False),
        gr.update(visible=False),
    )


def enable_run_button_for_method(method: str):
    """Enable the Run Analysis button only for fully implemented VaR methods."""
    return gr.update(interactive=(method in ("Historical VaR", "Parametric VaR")))


# ------------------------------------------------------------------
# UI builder
# ------------------------------------------------------------------


CUSTOM_CSS = """
.form { border: none !important; box-shadow: none !important; gap: 0 !important; }
.form .block, .form .row, .form > * { border: none !important; box-shadow: none !important; }
#excel-btn, #excel-btn.primary {
    background: #f97316 !important;
    background-color: #f97316 !important;
    color: white !important;
    border-color: #9a3412 !important;
    border: 1px solid #9a3412 !important;
}
#excel-btn:hover, #excel-btn.primary:hover {
    background: #ea580c !important;
    background-color: #ea580c !important;
    border-color: #9a3412 !important;
    border: 1px solid #9a3412 !important;
}
#portfolio-hr {
    margin: 2rem 0 0.5rem !important;
    border: none !important;
    border-top: 1px solid #e5e7eb !important;
}
#portfolio-footer {
    width: 100% !important;
    max-width: 100% !important;
}
#portfolio-text {
    text-align: center !important;
    margin: 0 auto !important;
    padding: 0.75rem 0 !important;
    width: 100% !important;
}
#portfolio-text a {
    color: #ffffff !important;
    font-weight: 500 !important;
    font-size: 0.8rem !important;
    font-family: 'Inter', 'Segoe UI', system-ui, sans-serif !important;
    letter-spacing: 0.05em !important;
    text-decoration: none !important;
    cursor: pointer !important;
}
#portfolio-text a:hover {
    color: #d1d5db !important;
}
"""


def build_app() -> gr.Blocks:
    """Construct and return the Gradio Blocks application."""

    with gr.Blocks(
        title="VaR Engine",
    ) as app:
        with gr.Row():
            with gr.Column(scale=3):
                gr.Markdown("# VaR Engine")
            with gr.Column(scale=1, min_width=260):
                download_file = gr.DownloadButton(
                    "Download Excel Report",
                    variant="primary",
                    visible=False,
                    elem_id="excel-btn",
                )

        with gr.Row():
            # Sidebar
            with gr.Column(scale=1, min_width=260):
                gr.Markdown("### Inputs")
                with gr.Group():
                    ticker_dd = gr.Dropdown(
                        choices=TICKERS,
                        value=TICKERS[0],
                        label="Ticker",
                    )
                    end_date_input = gr.DateTime(
                        include_time=False,
                        type="datetime",
                        label="VaR Date",
                    )
                    portfolio_val_input = gr.Number(
                        value=1000000,
                        label="Portfolio Value ($)",
                    )
                    n_days_slider = gr.Slider(
                        minimum=1,
                        maximum=15,
                        step=1,
                        value=10,
                        label="N Days for VaR",
                    )
                    with gr.Row():
                        confidence_dd = gr.Dropdown(
                            choices=["99%", "97.5%", "95%"],
                            value="99%",
                            label="VaR Confidence",
                            min_width=100,
                        )
                        es_confidence_dd = gr.Dropdown(
                            choices=["99%", "97.5%", "95%"],
                            value="99%",
                            label="ES Confidence",
                            min_width=100,
                        )
                    method_radio = gr.Radio(
                        choices=[
                            "Historical VaR",
                            "Parametric VaR",
                        ],
                        value="Historical VaR",
                        label="Method",
                    )
                run_btn = gr.Button("Run Analysis", variant="primary")

                # Enable/disable run button based on method availability
                method_radio.change(
                    fn=enable_run_button_for_method,
                    inputs=method_radio,
                    outputs=run_btn,
                )
            with gr.Column(scale=3):
                gr.Markdown("### Results")
                with gr.Row():
                    with gr.Column(scale=1):
                        var_box = gr.Textbox(
                            label="10-day 99% VaR",
                            interactive=False,
                        )
                    with gr.Column(scale=1):
                        es_box = gr.Textbox(
                            label="10-day 99% ES",
                            interactive=False,
                        )
                with gr.Row():
                    with gr.Column(scale=1):
                        stressed_var_box = gr.Textbox(
                            label="10-day 99% Stressed VaR",
                            interactive=False,
                        )
                    with gr.Column(scale=1):
                        stressed_es_box = gr.Textbox(
                            label="10-day 99% Stressed ES",
                            interactive=False,
                        )

                plot_dist = gr.Plot(show_label=False, visible=False)

        # Wiring
        all_outputs = [var_box, es_box, stressed_var_box, stressed_es_box, plot_dist, download_file]

        run_btn.click(
            fn=calculate_var_analysis,
            inputs=[
                ticker_dd,
                end_date_input,
                portfolio_val_input,
                n_days_slider,
                confidence_dd,
                es_confidence_dd,
                method_radio,
            ],
            outputs=all_outputs,
        )

        all_inputs = [
            ticker_dd,
            end_date_input,
            portfolio_val_input,
            n_days_slider,
            confidence_dd,
            es_confidence_dd,
            method_radio,
        ]

        label_inputs = [n_days_slider, confidence_dd, es_confidence_dd, method_radio]

        for comp in all_inputs:
            if comp is n_days_slider:
                comp.release(
                    fn=reset_analysis_results,
                    inputs=label_inputs,
                    outputs=all_outputs,
                )
            else:
                comp.change(
                    fn=reset_analysis_results,
                    inputs=label_inputs,
                    outputs=all_outputs,
                )

        method_radio.change(
            fn=enable_run_button_for_method, inputs=method_radio, outputs=run_btn
        )

        gr.HTML(
            '<hr id="portfolio-hr">'
            '<p id="portfolio-text">'
            '<a href="https://kameshcodes.github.io/portfolio/" target="_blank">'
            "\u00a9 kameshcodes"
            "</a></p>",
            elem_id="portfolio-footer",
        )

    return app


# ------------------------------------------------------------------
# Entry point
# ------------------------------------------------------------------

if __name__ == "__main__":
    port = int(os.environ.get("PORT", 7860))

    application = build_app()
    application.launch(server_name="0.0.0.0", server_port=port, share=False, theme=gr.themes.Base(), css=CUSTOM_CSS)