Download monitor2.py from showeed/customkun_any: direct link, hf CLI and curl.
- Browser
- Download file 20.3 kB
-
https://huggingface.co/datasets/showeed/customkun_any/resolve/main/monitor2.py
- Command line
-
hf download hf://datasets/showeed/customkun_any/monitor2.py
-
curl -L -o monitor2.py https://huggingface.co/datasets/showeed/customkun_any/resolve/main/monitor2.py
20.3 kB
| 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, | |
| } |