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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
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
import numpy as np
import pandas as pd


def format_trade_monitor_result(
    result,
    *,
    country_col,
    value_label="取引額",
    quantity_label="統計数量",
    value_unit=None,
    quantity_unit=None,
    pct_digits=1,
    number_digits=0,
):
    """
    monitor_trade() の返り値を、人間が読みやすい日本語表記に変換する。

    元の result は変更しない。

    Parameters
    ----------
    result : dict
        monitor_trade() の返り値

    country_col : str
        原産国カラム名
        例: "原産国"

    value_label : str
        金額の表示名
        例: "取引額", "課税価格"

    quantity_label : str
        数量の表示名
        例: "統計数量"

    value_unit : str or None
        金額単位
        例: "円", "千円"

    quantity_unit : str or None
        数量単位
        例: "KG", "MT", "NO"

    pct_digits : int
        %表示の小数点桁数

    number_digits : int
        金額・数量表示の小数点桁数

    Returns
    -------
    dict

    {
        "概要": DataFrame,
        "月次推移": DataFrame,
        "全体指標": DataFrame,
        "集中度": DataFrame,
        "国別一覧": DataFrame,
        "金額TOP": DataFrame,
        "数量TOP": DataFrame,
        "新規・消失国": DataFrame,
    }
    """

    # ============================================================
    # 表示用ヘルパー
    # ============================================================

    def is_missing(x):
        try:
            return pd.isna(x)
        except Exception:
            return False

    def fmt_number(x, unit=None, signed=False):
        if is_missing(x):
            return "-"

        if np.isposinf(x):
            return "+∞"

        if np.isneginf(x):
            return "-∞"

        sign = "+" if signed and x > 0 else ""

        text = f"{sign}{x:,.{number_digits}f}"

        if unit:
            text += f" {unit}"

        return text

    def fmt_pct(x):
        """
        0.253 -> +25.3%
        -0.12 -> -12.0%
        """
        if is_missing(x):
            return "-"

        if np.isposinf(x):
            return "+∞"

        if np.isneginf(x):
            return "-∞"

        return f"{x * 100:+.{pct_digits}f}%"

    def fmt_share(x):
        """
        シェア用。
        0.253 -> 25.3%
        """
        if is_missing(x):
            return "-"

        return f"{x * 100:.{pct_digits}f}%"

    def fmt_pp(x):
        """
        既に percentage point に変換済みの値。
        15.2 -> +15.2pt
        """
        if is_missing(x):
            return "-"

        return f"{x:+.{pct_digits}f}pt"

    def fmt_z(x):
        if is_missing(x):
            return "-"

        if np.isposinf(x):
            return "+∞"

        if np.isneginf(x):
            return "-∞"

        return f"{x:+.2f}"

    def fmt_hhi(x):
        if is_missing(x):
            return "-"

        return f"{x:.3f}"

    def fmt_effective_supplier(x):
        if is_missing(x):
            return "-"

        return f"{x:.2f}"

    def fmt_count(x):
        if is_missing(x):
            return "-"

        return f"{int(x):,}"

    def fmt_rank(x):
        if is_missing(x):
            return "-"

        return f"{int(x)}位"

    def fmt_rank_change(x):
        if is_missing(x):
            return "-"

        x = int(x)

        if x > 0:
            return f"{x}位上昇"

        if x < 0:
            return f"{abs(x)}位低下"

        return "変化なし"

    def fmt_status(x):
        mapping = {
            "new": "新規",
            "disappeared": "消失",
            "continuing": "継続",
        }

        return mapping.get(x, x)

    # ============================================================
    # 0. 概要
    # ============================================================

    warnings = result.get("warnings", [])

    summary = pd.DataFrame(
        {
            "対象月": [
                result.get("target_month", "-")
            ],
            "比較対象(前年同月)": [
                result.get("yoy_month", "-")
            ],
            "警告": [
                " / ".join(warnings)
                if warnings
                else "なし"
            ],
        }
    )

    # ============================================================
    # 1. 月次推移
    # ============================================================

    monthly = result["monthly"].copy()

    monthly_columns = {
        "month": "年月",
        "value": value_label,
        "quantity": quantity_label,
        "unit_price": "平均単価",
    }

    monthly = monthly.rename(
        columns=monthly_columns
    )

    if value_label in monthly.columns:
        monthly[value_label] = monthly[
            value_label
        ].map(
            lambda x: fmt_number(
                x,
                value_unit
            )
        )

    if quantity_label in monthly.columns:
        monthly[quantity_label] = monthly[
            quantity_label
        ].map(
            lambda x: fmt_number(
                x,
                quantity_unit
            )
        )

    unit_price_unit = None

    if value_unit and quantity_unit:
        unit_price_unit = (
            f"{value_unit}/{quantity_unit}"
        )

    if "平均単価" in monthly.columns:
        monthly["平均単価"] = monthly[
            "平均単価"
        ].map(
            lambda x: fmt_number(
                x,
                unit_price_unit
            )
        )

    monthly["年月"] = (
        monthly["年月"]
        .astype(str)
    )

    # ============================================================
    # 2. 全体指標
    # ============================================================

    metric = result[
        "metric_summary"
    ].copy()

    metric_names = {
        "value": value_label,
        "quantity": quantity_label,
        "unit_price": "平均単価",
    }

    metric_rows = []

    for metric_name, display_name in metric_names.items():

        if metric_name not in metric.index:
            continue

        row = metric.loc[
            metric_name
        ]

        if metric_name == "value":
            unit = value_unit

        elif metric_name == "quantity":
            unit = quantity_unit

        else:
            unit = unit_price_unit

        metric_rows.append(
            {
                "指標":
                    display_name,

                "当月値":
                    fmt_number(
                        row["current"],
                        unit
                    ),

                "前年同月値":
                    fmt_number(
                        row["yoy_base"],
                        unit
                    ),

                "前年同月比":
                    fmt_pct(
                        row["yoy_pct"]
                    ),

                "前月比":
                    fmt_pct(
                        row["mom_pct"]
                    ),

                "直近3か月平均比":
                    fmt_pct(
                        row[
                            "vs_prev3m_avg_pct"
                        ]
                    ),

                "過去12か月中央値比":
                    fmt_pct(
                        row[
                            "vs_prev12m_median_pct"
                        ]
                    ),

                "異常度(Robust Z)":
                    fmt_z(
                        row[
                            "robust_z_12m"
                        ]
                    ),
            }
        )

    metric_readable = pd.DataFrame(
        metric_rows
    )

    # ============================================================
    # 3. 集中度
    # ============================================================

    concentration = result[
        "concentration"
    ].copy()

    concentration_rows = []

    basis_names = {
        "value": "金額ベース",
        "quantity": "数量ベース",
    }

    for basis, display_name in basis_names.items():

        if basis not in concentration.index:
            continue

        row = concentration.loc[
            basis
        ]

        concentration_rows.append(
            {
                "集計基準":
                    display_name,

                "CR1(当月)":
                    fmt_share(
                        row["cr1_current"]
                    ),

                "CR1(前年同月)":
                    fmt_share(
                        row["cr1_yoy_base"]
                    ),

                "CR1前年差":
                    fmt_pp(
                        row["cr1_delta_pp"]
                    ),

                "CR3(当月)":
                    fmt_share(
                        row["cr3_current"]
                    ),

                "CR3(前年同月)":
                    fmt_share(
                        row["cr3_yoy_base"]
                    ),

                "CR3前年差":
                    fmt_pp(
                        row["cr3_delta_pp"]
                    ),

                "CR5(当月)":
                    fmt_share(
                        row["cr5_current"]
                    ),

                "CR5(前年同月)":
                    fmt_share(
                        row["cr5_yoy_base"]
                    ),

                "CR5前年差":
                    fmt_pp(
                        row["cr5_delta_pp"]
                    ),

                "HHI(当月)":
                    fmt_hhi(
                        row["hhi_current"]
                    ),

                "HHI(前年同月)":
                    fmt_hhi(
                        row["hhi_yoy_base"]
                    ),

                "HHI前年差":
                    fmt_hhi(
                        row["hhi_delta"]
                    ),

                "有効供給国数(当月)":
                    fmt_effective_supplier(
                        row[
                            "effective_suppliers_current"
                        ]
                    ),

                "有効供給国数(前年同月)":
                    fmt_effective_supplier(
                        row[
                            "effective_suppliers_yoy_base"
                        ]
                    ),

                "実供給国数(当月)":
                    fmt_count(
                        row[
                            "supplier_count_current"
                        ]
                    ),

                "実供給国数(前年同月)":
                    fmt_count(
                        row[
                            "supplier_count_yoy_base"
                        ]
                    ),

                "供給構造変化指数":
                    fmt_share(
                        row[
                            "structure_change_index"
                        ]
                    ),
            }
        )

    concentration_readable = pd.DataFrame(
        concentration_rows
    )

    # ============================================================
    # 4. 国別テーブル共通処理
    # ============================================================

    def format_country_table(df):

        df = df.copy()

        # -------------------------------
        # 数値フォーマット
        # -------------------------------

        value_number_cols = [
            "value_current",
            "value_yoy_base",
        ]

        value_signed_cols = [
            "value_delta",
        ]

        quantity_number_cols = [
            "quantity_current",
            "quantity_yoy_base",
        ]

        quantity_signed_cols = [
            "quantity_delta",
        ]

        pct_cols = [
            "value_yoy_pct",
            "quantity_yoy_pct",
            "unit_price_yoy_pct",
        ]

        share_cols = [
            "value_share_current",
            "value_share_yoy_base",
            "quantity_share_current",
            "quantity_share_yoy_base",
        ]

        pp_cols = [
            "value_share_delta_pp",
            "quantity_share_delta_pp",
        ]

        rank_cols = [
            "value_rank_current",
            "value_rank_yoy_base",
            "quantity_rank_current",
            "quantity_rank_yoy_base",
        ]

        rank_change_cols = [
            "value_rank_change",
            "quantity_rank_change",
        ]

        unit_price_cols = [
            "unit_price_current",
            "unit_price_yoy_base",
        ]

        for col in value_number_cols:
            if col in df.columns:
                df[col] = df[col].map(
                    lambda x: fmt_number(
                        x,
                        value_unit
                    )
                )

        for col in value_signed_cols:
            if col in df.columns:
                df[col] = df[col].map(
                    lambda x: fmt_number(
                        x,
                        value_unit,
                        signed=True,
                    )
                )

        for col in quantity_number_cols:
            if col in df.columns:
                df[col] = df[col].map(
                    lambda x: fmt_number(
                        x,
                        quantity_unit
                    )
                )

        for col in quantity_signed_cols:
            if col in df.columns:
                df[col] = df[col].map(
                    lambda x: fmt_number(
                        x,
                        quantity_unit,
                        signed=True,
                    )
                )

        for col in pct_cols:
            if col in df.columns:
                df[col] = df[col].map(
                    fmt_pct
                )

        for col in share_cols:
            if col in df.columns:
                df[col] = df[col].map(
                    fmt_share
                )

        for col in pp_cols:
            if col in df.columns:
                df[col] = df[col].map(
                    fmt_pp
                )

        for col in rank_cols:
            if col in df.columns:
                df[col] = df[col].map(
                    fmt_rank
                )

        for col in rank_change_cols:
            if col in df.columns:
                df[col] = df[col].map(
                    fmt_rank_change
                )

        for col in unit_price_cols:
            if col in df.columns:
                df[col] = df[col].map(
                    lambda x: fmt_number(
                        x,
                        unit_price_unit
                    )
                )

        if "status" in df.columns:
            df["status"] = df[
                "status"
            ].map(
                fmt_status
            )

        if "event_flag" in df.columns:
            df["event_flag"] = np.where(
                df["event_flag"],
                "注目",
                "",
            )

        # -------------------------------
        # 日本語ヘッダー
        # -------------------------------

        column_names = {

            country_col:
                country_col,

            "value_current":
                f"{value_label}(当月)",

            "value_yoy_base":
                f"{value_label}(前年同月)",

            "value_delta":
                f"{value_label}前年差",

            "value_yoy_pct":
                f"{value_label}前年同月比",

            "value_share_current":
                f"{value_label}シェア(当月)",

            "value_share_yoy_base":
                f"{value_label}シェア(前年同月)",

            "value_share_delta_pp":
                f"{value_label}シェア前年差",

            "value_rank_current":
                "金額順位(当月)",

            "value_rank_yoy_base":
                "金額順位(前年同月)",

            "value_rank_change":
                "金額順位変化",

            "quantity_current":
                f"{quantity_label}(当月)",

            "quantity_yoy_base":
                f"{quantity_label}(前年同月)",

            "quantity_delta":
                f"{quantity_label}前年差",

            "quantity_yoy_pct":
                f"{quantity_label}前年同月比",

            "quantity_share_current":
                f"{quantity_label}シェア(当月)",

            "quantity_share_yoy_base":
                f"{quantity_label}シェア(前年同月)",

            "quantity_share_delta_pp":
                f"{quantity_label}シェア前年差",

            "quantity_rank_current":
                "数量順位(当月)",

            "quantity_rank_yoy_base":
                "数量順位(前年同月)",

            "quantity_rank_change":
                "数量順位変化",

            "unit_price_current":
                "平均単価(当月)",

            "unit_price_yoy_base":
                "平均単価(前年同月)",

            "unit_price_yoy_pct":
                "平均単価前年同月比",

            "status":
                "供給状態",

            "event_flag":
                "注目フラグ",
        }

        df = df.rename(
            columns=column_names
        )

        # -------------------------------
        # 列順を人間向けに整理
        # -------------------------------

        desired_order = [

            country_col,

            f"{value_label}(当月)",
            f"{value_label}(前年同月)",
            f"{value_label}前年差",
            f"{value_label}前年同月比",

            f"{value_label}シェア(当月)",
            f"{value_label}シェア(前年同月)",
            f"{value_label}シェア前年差",

            "金額順位(当月)",
            "金額順位(前年同月)",
            "金額順位変化",

            f"{quantity_label}(当月)",
            f"{quantity_label}(前年同月)",
            f"{quantity_label}前年差",
            f"{quantity_label}前年同月比",

            f"{quantity_label}シェア(当月)",
            f"{quantity_label}シェア(前年同月)",
            f"{quantity_label}シェア前年差",

            "数量順位(当月)",
            "数量順位(前年同月)",
            "数量順位変化",

            "平均単価(当月)",
            "平均単価(前年同月)",
            "平均単価前年同月比",

            "供給状態",
            "注目フラグ",
        ]

        desired_order = [
            col
            for col in desired_order
            if col in df.columns
        ]

        other_cols = [
            col
            for col in df.columns
            if col not in desired_order
        ]

        return df[
            desired_order
            + other_cols
        ].reset_index(drop=True)

    # ============================================================
    # 5. 各国別テーブル
    # ============================================================

    country_all = format_country_table(
        result["country_all"]
    )

    country_top_value = format_country_table(
        result["country_top_value"]
    )

    country_top_quantity = format_country_table(
        result["country_top_quantity"]
    )

    events = format_country_table(
        result["events"]
    )

    # ============================================================
    # Return
    # ============================================================

    return {
        "概要":
            summary,

        "月次推移":
            monthly,

        "全体指標":
            metric_readable,

        "集中度":
            concentration_readable,

        "国別一覧":
            country_all,

        "金額TOP":
            country_top_value,

        "数量TOP":
            country_top_quantity,

        "新規・消失国":
            events,
    }