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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# app.py

import pandas as pd
import gradio as gr

# ---------------------------------------------------
# HELPERS
# ---------------------------------------------------

from helper.vintage_helpers import (
    create_booking_vintage
)

from helper.data_merger import (
    merge_acq_perf
)

# ---------------------------------------------------
# METRICS
# ---------------------------------------------------

from metrics.mix_metrics import (
    calculate_vintage_mix,
    calculate_limit_mix
)

# ---------------------------------------------------
# ANALYTICS
# ---------------------------------------------------

from analytics.performance_analysis import (
    generate_metric_view
)

# ---------------------------------------------------
# VISUALIZATIONS - VINTAGE CURVES
# ---------------------------------------------------

from visualizations.vintage_curves import (
    generate_delinquency_metric_chart,
    generate_multi_metric_comparison,
    generate_segment_delinquency_curve
)

# ---------------------------------------------------
# VISUALIZATIONS - SEGMENT RANKING
# ---------------------------------------------------

from visualizations.segment_ranking import (
    generate_segment_risk_heatmap,
    generate_segment_risk_ranking,
    generate_multi_category_risk_comparison,
    calculate_portfolio_risk_summary
)

# ---------------------------------------------------
# LOAD DATA
# ---------------------------------------------------

acq = pd.read_csv(
    "data/acquisition.csv"
)

perf = pd.read_csv(
    "data/performance.csv"
)

# ---------------------------------------------------
# CREATE BOOKING VINTAGE
# ---------------------------------------------------

acq = create_booking_vintage(
    acq,
    booking_date_col="booking_date"
)

# ---------------------------------------------------
# CREATE MASTER PERFORMANCE DATASET
# ---------------------------------------------------

master_df = merge_acq_perf(
    acq_df=acq,
    perf_df=perf
)

# ---------------------------------------------------
# ACQUISITION ANALYSIS
# ---------------------------------------------------

def run_acquisition_analysis(
    analysis_type,
    category
):

    # -----------------------------------------
    # PORTFOLIO MIX
    # -----------------------------------------

    if analysis_type == "Portfolio Mix":

        result = (
            acq.groupby(
                ["booking_vintage", category]
            )
            .agg(
                count=("account_id", "nunique"),
                balance=("credit_limit", "sum")
            )
            .reset_index()
        )

        vintage_total = (
            result.groupby("booking_vintage")["count"]
            .transform("sum")
        )

        result["rate"] = (
            result["count"] / vintage_total
        ) * 100

        result["rate"] = (
            result["rate"]
            .round(2)
        )

    # -----------------------------------------
    # CREDIT LINE CONCENTRATION
    # -----------------------------------------

    elif analysis_type == "Credit Line Concentration":

        result = (
            acq.groupby(
                ["booking_vintage", category]
            )
            .agg(
                count=("account_id", "nunique"),
                balance=("credit_limit", "sum")
            )
            .reset_index()
        )

        vintage_total = (
            result.groupby("booking_vintage")["balance"]
            .transform("sum")
        )

        result["rate"] = (
            result["balance"] / vintage_total
        ) * 100

        result["rate"] = (
            result["rate"]
            .round(2)
        )

    else:

        return pd.DataFrame()

    # -----------------------------------------
    # STANDARDIZED OUTPUT
    # -----------------------------------------

    result = result.rename(
        columns={
            "booking_vintage": "Vintage",
            category: "Category",
            "count": "Count",
            "balance": "Balance",
            "rate": "Rate"
        }
    )

    return result[
        [
            "Vintage",
            "Category",
            "Count",
            "Balance",
            "Rate"
        ]
    ]

# ---------------------------------------------------
# PERFORMANCE ANALYSIS
# ---------------------------------------------------

def run_performance_analysis(
    metric_name,
    view_level
):

    # -----------------------------------------
    # VIEW MAPPING
    # -----------------------------------------

    view_mapping = {

        "Overall": None,

        "Channel":
        "sourcing_channel",

        "FICO":
        "fico_band",

        "City Tier":
        "city_tier",

        "Occupation":
        "occupation_type"
    }

    group_col = view_mapping[
        view_level
    ]

    # -----------------------------------------
    # CALL ANALYTICS ENGINE
    # -----------------------------------------

    result = generate_metric_view(
        df=master_df,
        metric_name=metric_name,
        group_col=group_col
    )

    # -----------------------------------------
    # STANDARDIZE OUTPUT
    # -----------------------------------------

    if group_col is not None:

        result = result.rename(
            columns={
                group_col: "Category"
            }
        )

    else:

        result["Category"] = "Overall"

    # -----------------------------------------
    # IDENTIFY RATE COLUMN
    # -----------------------------------------

    rate_col = [
        col for col in result.columns
        if "rate" in col.lower()
    ][0]

    # -----------------------------------------
    # OUTPUT FORMAT
    # -----------------------------------------

    final_result = pd.DataFrame()

    final_result["Vintage"] = (
        result["booking_vintage"]
    )

    final_result["Category"] = (
        result["Category"]
    )

    final_result["Count"] = (
        result["total_accounts"]
    )

    final_result["Balance"] = (
        result["total_balance"]
    )

    final_result["Rate"] = (
        result[rate_col]
        .round(2)
    )

    return final_result

# ---------------------------------------------------
# VINTAGE CURVES ANALYSIS
# ---------------------------------------------------

def generate_vintage_curve_single(
    metric_name
):
    """Generate single vintage curve for a metric."""
    try:
        fig = generate_delinquency_metric_chart(
            df=master_df,
            metric_name=metric_name,
            chart_type="line"
        )
        return fig
    except Exception as e:
        return f"Error generating vintage curve: {str(e)}"


def generate_vintage_curves_comparison():
    """Generate comparison of all vintage curves."""
    try:
        fig = generate_multi_metric_comparison(
            df=master_df,
            metrics=["30+@3", "30+@6", "60+@6", "Yr1 NCL"]
        )
        return fig
    except Exception as e:
        return f"Error generating comparison: {str(e)}"


def generate_segmented_vintage_curve(
    metric_name,
    category
):
    """Generate vintage curve segmented by category."""
    try:
        fig = generate_segment_delinquency_curve(
            df=master_df,
            metric_name=metric_name,
            category=category
        )
        return fig
    except Exception as e:
        return f"Error generating segmented curve: {str(e)}"

# ---------------------------------------------------
# SEGMENT RANKING ANALYSIS
# ---------------------------------------------------

def generate_segment_risk_heatmap_chart():
    """Generate risk heatmap across all segments and metrics."""
    try:
        fig = generate_segment_risk_heatmap(
            df=master_df
        )
        return fig
    except Exception as e:
        return f"Error generating heatmap: {str(e)}"


def generate_high_risk_segments_ranking(
    metric_name,
    category
):
    """Generate ranking of high-risk segments."""
    try:
        fig = generate_segment_risk_ranking(
            df=master_df,
            metric_name=metric_name,
            category=category,
            top_n=10
        )
        return fig
    except Exception as e:
        return f"Error generating ranking: {str(e)}"


def generate_multi_category_comparison(
    metric_name
):
    """Generate risk comparison across all categories."""
    try:
        fig = generate_multi_category_risk_comparison(
            df=master_df,
            metric_name=metric_name
        )
        return fig
    except Exception as e:
        return f"Error generating comparison: {str(e)}"


def generate_portfolio_summary():
    """Generate portfolio risk summary."""
    try:
        summary_df = calculate_portfolio_risk_summary(
            df=master_df
        )
        return summary_df
    except Exception as e:
        return f"Error generating summary: {str(e)}"

# ---------------------------------------------------
# DYNAMIC DROPDOWNS
# ---------------------------------------------------

def update_analysis_dropdown(
    dataset
):

    # -----------------------------------------
    # ACQUISITION
    # -----------------------------------------

    if dataset == "Acquisition":

        return gr.update(
            choices=[
                "Portfolio Mix",
                "Credit Line Concentration"
            ],
            value="Portfolio Mix"
        )

    # -----------------------------------------
    # PERFORMANCE
    # -----------------------------------------

    elif dataset == "Performance":

        return gr.update(
            choices=[
                "30+@3",
                "30+@6",
                "60+@6",
                "Yr1 NCL"
            ],
            value="30+@6"
        )


def update_category_dropdown(
    dataset
):

    # -----------------------------------------
    # ACQUISITION
    # -----------------------------------------

    if dataset == "Acquisition":

        return gr.update(
            choices=[
                "fico_band",
                "sourcing_channel",
                "city_tier",
                "occupation_type"
            ],
            value="fico_band"
        )

    # -----------------------------------------
    # PERFORMANCE
    # -----------------------------------------

    elif dataset == "Performance":

        return gr.update(
            choices=[
                "Overall",
                "Channel",
                "FICO",
                "City Tier",
                "Occupation"
            ],
            value="Overall"
        )

# ---------------------------------------------------
# MASTER ROUTER
# ---------------------------------------------------

def run_analysis(
    dataset,
    analysis,
    category
):

    # -----------------------------------------
    # ACQUISITION
    # -----------------------------------------

    if dataset == "Acquisition":

        return run_acquisition_analysis(
            analysis_type=analysis,
            category=category
        )

    # -----------------------------------------
    # PERFORMANCE
    # -----------------------------------------

    elif dataset == "Performance":

        return run_performance_analysis(
            metric_name=analysis,
            view_level=category
        )

    else:

        return pd.DataFrame()

# ---------------------------------------------------
# GRADIO UI
# ---------------------------------------------------

with gr.Blocks() as app:

    gr.Markdown(
        "# Risk Analytics Manager Agent - Phase 2"
    )

    with gr.Tabs():

        # =================================================
        # TAB 1: BASIC ANALYSIS (Phase 1)
        # =================================================

        with gr.TabItem("πŸ“Š Basic Analysis"):

            gr.Markdown(
                "## Phase 1: Acquisition & Performance Analysis"
            )

            with gr.Row():

                dataset_dropdown = gr.Dropdown(
                    choices=[
                        "Acquisition",
                        "Performance"
                    ],
                    value="Acquisition",
                    label="Dataset"
                )

                analysis_dropdown = gr.Dropdown(
                    choices=[
                        "Portfolio Mix",
                        "Credit Line Concentration"
                    ],
                    value="Portfolio Mix",
                    label="Analysis"
                )

                category_dropdown = gr.Dropdown(
                    choices=[
                        "fico_band",
                        "sourcing_channel",
                        "city_tier",
                        "occupation_type"
                    ],
                    value="fico_band",
                    label="Category / View"
                )

            # -----------------------------------------
            # DYNAMIC DROPDOWNS
            # -----------------------------------------

            dataset_dropdown.change(
                fn=update_analysis_dropdown,
                inputs=dataset_dropdown,
                outputs=analysis_dropdown
            )

            dataset_dropdown.change(
                fn=update_category_dropdown,
                inputs=dataset_dropdown,
                outputs=category_dropdown
            )

            # -----------------------------------------
            # RUN BUTTON
            # -----------------------------------------

            run_button = gr.Button(
                "Run Analysis",
                variant="primary"
            )

            output_table = gr.Dataframe()

            run_button.click(
                fn=run_analysis,
                inputs=[
                    dataset_dropdown,
                    analysis_dropdown,
                    category_dropdown
                ],
                outputs=output_table
            )

        # =================================================
        # TAB 2: VINTAGE CURVES (Phase 2)
        # =================================================

        with gr.TabItem("πŸ“ˆ Vintage Curves"):

            gr.Markdown(
                "## Phase 2: Vintage Delinquency Curves Analysis"
            )

            with gr.Row():

                metric_dropdown = gr.Dropdown(
                    choices=[
                        "30+@3",
                        "30+@6",
                        "60+@6",
                        "Yr1 NCL"
                    ],
                    value="30+@6",
                    label="Delinquency Metric"
                )

                vintage_chart_type = gr.Radio(
                    choices=["Single Metric", "All Metrics Comparison"],
                    value="Single Metric",
                    label="Chart Type"
                )

            def update_vintage_view(metric, chart_type):
                if chart_type == "Single Metric":
                    return generate_vintage_curve_single(metric)
                else:
                    return generate_vintage_curves_comparison()

            vintage_chart = gr.Plot(
                label="Vintage Curve"
            )

            gen_vintage_btn = gr.Button(
                "Generate Vintage Curve",
                variant="primary"
            )

            gen_vintage_btn.click(
                fn=update_vintage_view,
                inputs=[metric_dropdown, vintage_chart_type],
                outputs=vintage_chart
            )

            gr.Markdown(
                "### Segmented Vintage Curves"
            )

            with gr.Row():

                segment_metric = gr.Dropdown(
                    choices=[
                        "30+@3",
                        "30+@6",
                        "60+@6",
                        "Yr1 NCL"
                    ],
                    value="30+@6",
                    label="Metric"
                )

                segment_category = gr.Dropdown(
                    choices=[
                        "fico_band",
                        "sourcing_channel",
                        "city_tier",
                        "occupation_type"
                    ],
                    value="fico_band",
                    label="Category"
                )

            segmented_chart = gr.Plot(
                label="Segmented Vintage Curve"
            )

            gen_segment_btn = gr.Button(
                "Generate Segmented Curve",
                variant="primary"
            )

            gen_segment_btn.click(
                fn=generate_segmented_vintage_curve,
                inputs=[segment_metric, segment_category],
                outputs=segmented_chart
            )

        # =================================================
        # TAB 3: SEGMENT RANKING (Phase 2)
        # =================================================

        with gr.TabItem("⚠️ Segment Ranking"):

            gr.Markdown(
                "## Phase 2: High-Risk Segment Analysis"
            )

            # --------- HEATMAP SECTION ---------

            gr.Markdown(
                "### πŸ”₯ Overall Risk Heatmap"
            )

            gr.Markdown(
                "Risk scores across all delinquency metrics and segments"
            )

            heatmap_chart = gr.Plot(
                label="Risk Heatmap"
            )

            gen_heatmap_btn = gr.Button(
                "Generate Risk Heatmap",
                variant="primary"
            )

            gen_heatmap_btn.click(
                fn=generate_segment_risk_heatmap_chart,
                outputs=heatmap_chart
            )

            gr.Markdown(
                "---"
            )

            # --------- HIGH-RISK RANKING SECTION ---------

            gr.Markdown(
                "### πŸ“Š High-Risk Segments Ranking"
            )

            with gr.Row():

                ranking_metric = gr.Dropdown(
                    choices=[
                        "30+@3",
                        "30+@6",
                        "60+@6",
                        "Yr1 NCL"
                    ],
                    value="30+@6",
                    label="Metric"
                )

                ranking_category = gr.Dropdown(
                    choices=[
                        "fico_band",
                        "sourcing_channel",
                        "city_tier",
                        "occupation_type"
                    ],
                    value="fico_band",
                    label="Category"
                )

            ranking_chart = gr.Plot(
                label="High-Risk Segments"
            )

            gen_ranking_btn = gr.Button(
                "Generate Risk Ranking",
                variant="primary"
            )

            gen_ranking_btn.click(
                fn=generate_high_risk_segments_ranking,
                inputs=[ranking_metric, ranking_category],
                outputs=ranking_chart
            )

            gr.Markdown(
                "---"
            )

            # --------- MULTI-CATEGORY COMPARISON ---------

            gr.Markdown(
                "### πŸ”€ Cross-Category Risk Comparison"
            )

            comparison_metric = gr.Dropdown(
                choices=[
                    "30+@3",
                    "30+@6",
                    "60+@6",
                    "Yr1 NCL"
                ],
                value="30+@6",
                label="Metric"
            )

            comparison_chart = gr.Plot(
                label="Multi-Category Comparison"
            )

            gen_comparison_btn = gr.Button(
                "Generate Comparison",
                variant="primary"
            )

            gen_comparison_btn.click(
                fn=generate_multi_category_comparison,
                inputs=comparison_metric,
                outputs=comparison_chart
            )

            gr.Markdown(
                "---"
            )

            # --------- PORTFOLIO SUMMARY ---------

            gr.Markdown(
                "### πŸ“‹ Portfolio Risk Summary"
            )

            summary_table = gr.Dataframe(
                label="Risk Summary"
            )

            gen_summary_btn = gr.Button(
                "Generate Summary",
                variant="primary"
            )

            gen_summary_btn.click(
                fn=generate_portfolio_summary,
                outputs=summary_table
            )

app.launch()