customkun_any / monitor.py
showeed's picture
Create monitor.py
b5265a7 verified
Raw History Blame Contribute Delete
24.3 kB
import numpy as np
import pandas as pd
from typing import Optional, Dict, Any
def _safe_change(current, base):
"""
増減率 current / base - 1
base=0 の場合は NaN
"""
if pd.isna(current) or pd.isna(base) or base == 0:
return np.nan
return current / base - 1.0
def _robust_z(current, history):
"""
Median / MAD を使った Robust Z-score
"""
x = (
pd.Series(history, dtype="float64")
.replace([np.inf, -np.inf], np.nan)
.dropna()
)
if len(x) == 0 or pd.isna(current):
return np.nan
median = x.median()
mad = (x - median).abs().median()
if mad == 0:
if current == median:
return 0.0
return np.inf if current > median else -np.inf
return (current - median) / (1.4826 * mad)
def _normalize_month(series):
"""
以下のような年月表現を Period[M] に統一
202608
"202608"
"2026-08"
datetime
"""
if isinstance(series.dtype, pd.PeriodDtype):
return series.dt.asfreq("M")
if pd.api.types.is_datetime64_any_dtype(series):
return series.dt.to_period("M")
text = series.astype(str).str.strip()
is_yyyymm = text.str.fullmatch(r"\d{6}")
out = pd.Series(
pd.NaT,
index=series.index,
dtype="datetime64[ns]"
)
if is_yyyymm.any():
out.loc[is_yyyymm] = pd.to_datetime(
text.loc[is_yyyymm],
format="%Y%m",
errors="coerce"
)
if (~is_yyyymm).any():
out.loc[~is_yyyymm] = pd.to_datetime(
text.loc[~is_yyyymm],
errors="coerce"
)
return out.dt.to_period("M")
def monitor_trade(
df: pd.DataFrame,
*,
month_col: str,
country_col: str,
value_col: str,
quantity_col: str,
target_month: Optional[str] = None,
quantity_unit_col: Optional[str] = None,
top_n: int = 10,
event_min_share: float = 0.0,
event_min_value: float = 0.0,
) -> Dict[str, Any]:
"""
貿易統計モニタリング用集計関数
想定:
対象HSについて、
分析対象月 + 過去12か月
= 合計13か月分の輸入申告データを渡す。
Parameters
----------
df:
輸入申告DataFrame
month_col:
年月カラム
例: "年月"
country_col:
原産国カラム
例: "原産国"
value_col:
取引額カラム
例: "課税価格"
quantity_col:
統計数量カラム
例: "統計数量"
target_month:
分析対象月
例: "2026-08"
Noneの場合はdf内の最新月
quantity_unit_col:
統計数量単位
例: "統計数量単位"
指定した場合、複数単位が混在していればエラーにする。
top_n:
国別ランキング表示件数
event_min_share:
新規国・消失国として抽出する最低シェア
例:
0.01 = 1%
event_min_value:
新規国・消失国として抽出する最低金額
Returns
-------
dict
{
"target_month":
分析対象月
"yoy_month":
前年同月
"monthly":
過去13か月の月次推移
"metric_summary":
金額・数量・単価の
YoY / MoM / 3か月平均比 /
12か月中央値比 / Robust Z
"concentration":
CR1 / CR3 / CR5 / HHI /
有効供給国数 / 構造変化指数
"country_all":
全原産国比較
"country_top_value":
金額TOP N
"country_top_quantity":
数量TOP N
"events":
新規国・消失国
"warnings":
警告
}
"""
# -------------------------------------------------
# カラム確認
# -------------------------------------------------
required_cols = [
month_col,
country_col,
value_col,
quantity_col,
]
if quantity_unit_col is not None:
required_cols.append(quantity_unit_col)
missing_cols = [
c for c in required_cols
if c not in df.columns
]
if missing_cols:
raise KeyError(
f"存在しないカラムがあります: {missing_cols}"
)
# -------------------------------------------------
# 必要列のみコピー
# -------------------------------------------------
x = df[required_cols].copy()
x["_month"] = _normalize_month(
x[month_col]
)
x["_value"] = pd.to_numeric(
x[value_col],
errors="coerce"
)
x["_quantity"] = pd.to_numeric(
x[quantity_col],
errors="coerce"
)
x["_country"] = (
x[country_col]
.astype("string")
.fillna("(不明)")
)
x = x.dropna(
subset=[
"_month",
"_value",
"_quantity"
]
)
if x.empty:
raise ValueError(
"有効なデータがありません。"
"年月・金額・数量カラムを確認してください。"
)
# -------------------------------------------------
# 分析対象月
# -------------------------------------------------
if target_month is None:
target = x["_month"].max()
else:
target = pd.Period(
target_month,
freq="M"
)
start_month = target - 12
yoy_month = target - 12
prev_month = target - 1
# 13か月分に限定
x = x[
x["_month"].between(
start_month,
target
)
].copy()
if x.empty:
raise ValueError(
f"{start_month}〜{target} の"
"データがありません。"
)
# -------------------------------------------------
# 統計数量単位チェック
# -------------------------------------------------
if quantity_unit_col is not None:
units = (
x[quantity_unit_col]
.dropna()
.astype(str)
.unique()
)
if len(units) > 1:
raise ValueError(
"統計数量の単位が複数あります。\n"
f"{list(units)}\n"
"単位ごと、またはHSごとに分けて"
"集計してください。"
)
# -------------------------------------------------
# 13か月存在確認
# -------------------------------------------------
expected_months = pd.period_range(
start=start_month,
end=target,
freq="M"
)
months_present = set(
x["_month"].unique()
)
missing_months = [
str(m)
for m in expected_months
if m not in months_present
]
warnings = []
if missing_months:
warnings.append(
"対象HSのレコードがない月を"
"0として扱いました: "
+ ", ".join(missing_months)
)
# =================================================
# 1. 月次全体集計
# =================================================
monthly = (
x
.groupby(
"_month",
observed=True
)
.agg(
value=(
"_value",
"sum"
),
quantity=(
"_quantity",
"sum"
),
)
.reindex(
expected_months,
fill_value=0.0
)
)
monthly.index.name = "month"
monthly["unit_price"] = (
monthly["value"]
.div(
monthly["quantity"]
.replace(0, np.nan)
)
)
# =================================================
# 2. 全体指標
# =================================================
summary_rows = []
for metric in [
"value",
"quantity",
"unit_price",
]:
s = monthly[metric]
current = s.loc[target]
yoy_base = s.loc[yoy_month]
mom_base = s.loc[prev_month]
history_12m = s.loc[
start_month:prev_month
]
previous_3m = s.loc[
target - 3:prev_month
]
summary_rows.append(
{
"metric": metric,
"current":
current,
"yoy_base":
yoy_base,
# 前年同月比
"yoy_pct":
_safe_change(
current,
yoy_base
),
# 前月比
"mom_pct":
_safe_change(
current,
mom_base
),
# 直近3か月平均比
"vs_prev3m_avg_pct":
_safe_change(
current,
previous_3m.mean()
),
# 過去12か月中央値比
"vs_prev12m_median_pct":
_safe_change(
current,
history_12m.median()
),
# Robust Z
"robust_z_12m":
_robust_z(
current,
history_12m
),
}
)
metric_summary = (
pd.DataFrame(summary_rows)
.set_index("metric")
)
# =================================================
# 3. 国別集計
# =================================================
grouped = (
x
.groupby(
[
"_month",
"_country",
],
observed=True,
)
.agg(
value=(
"_value",
"sum"
),
quantity=(
"_quantity",
"sum"
),
)
.reset_index()
)
# 対象月
current_country = (
grouped[
grouped["_month"] == target
][
[
"_country",
"value",
"quantity",
]
]
.rename(
columns={
"value":
"value_current",
"quantity":
"quantity_current",
}
)
)
# 前年同月
previous_country = (
grouped[
grouped["_month"] == yoy_month
][
[
"_country",
"value",
"quantity",
]
]
.rename(
columns={
"value":
"value_yoy_base",
"quantity":
"quantity_yoy_base",
}
)
)
# 外部結合
country = (
current_country
.merge(
previous_country,
on="_country",
how="outer"
)
.fillna(
{
"value_current": 0.0,
"quantity_current": 0.0,
"value_yoy_base": 0.0,
"quantity_yoy_base": 0.0,
}
)
)
# =================================================
# 4. 国別 金額 / 数量 共通指標
# =================================================
for prefix in [
"value",
"quantity",
]:
current = country[
f"{prefix}_current"
]
previous = country[
f"{prefix}_yoy_base"
]
current_total = current.sum()
previous_total = previous.sum()
# 差分
country[
f"{prefix}_delta"
] = (
current
- previous
)
# YoY
country[
f"{prefix}_yoy_pct"
] = np.where(
previous != 0,
current / previous - 1,
np.nan
)
# シェア
if current_total > 0:
country[
f"{prefix}_share_current"
] = (
current
/ current_total
)
else:
country[
f"{prefix}_share_current"
] = 0.0
if previous_total > 0:
country[
f"{prefix}_share_yoy_base"
] = (
previous
/ previous_total
)
else:
country[
f"{prefix}_share_yoy_base"
] = 0.0
# シェア前年差
country[
f"{prefix}_share_delta_pp"
] = (
country[
f"{prefix}_share_current"
]
-
country[
f"{prefix}_share_yoy_base"
]
) * 100
# 順位
country[
f"{prefix}_rank_current"
] = (
current
.where(current > 0)
.rank(
method="min",
ascending=False
)
)
country[
f"{prefix}_rank_yoy_base"
] = (
previous
.where(previous > 0)
.rank(
method="min",
ascending=False
)
)
# 正なら順位上昇
country[
f"{prefix}_rank_change"
] = (
country[
f"{prefix}_rank_yoy_base"
]
-
country[
f"{prefix}_rank_current"
]
)
# =================================================
# 5. 国別単価
# =================================================
country["unit_price_current"] = (
country["value_current"]
.div(
country[
"quantity_current"
]
.replace(
0,
np.nan
)
)
)
country["unit_price_yoy_base"] = (
country["value_yoy_base"]
.div(
country[
"quantity_yoy_base"
]
.replace(
0,
np.nan
)
)
)
country["unit_price_yoy_pct"] = (
country[
"unit_price_current"
]
.div(
country[
"unit_price_yoy_base"
]
)
.sub(1)
)
# =================================================
# 6. 新規 / 消失国
# =================================================
country["status"] = np.select(
[
(
country["value_current"] > 0
)
&
(
country["value_yoy_base"] == 0
),
(
country["value_current"] == 0
)
&
(
country["value_yoy_base"] > 0
),
],
[
"new",
"disappeared",
],
default="continuing"
)
# 新規・消失国のうち
# ある程度重要なものだけ抽出可能
country["event_flag"] = (
(
country["status"]
!= "continuing"
)
&
(
(
country[
[
"value_share_current",
"value_share_yoy_base",
]
]
.max(axis=1)
>= event_min_share
)
|
(
country[
[
"value_current",
"value_yoy_base",
]
]
.max(axis=1)
>= event_min_value
)
)
)
# =================================================
# 7. 集中度
# =================================================
def concentration(prefix):
current_share = country[
f"{prefix}_share_current"
]
previous_share = country[
f"{prefix}_share_yoy_base"
]
current_values = country[
f"{prefix}_current"
]
previous_values = country[
f"{prefix}_yoy_base"
]
current_total = (
current_values.sum()
)
previous_total = (
previous_values.sum()
)
def calc_one(
shares,
values,
total,
):
if total <= 0:
return {
"cr1": np.nan,
"cr3": np.nan,
"cr5": np.nan,
"hhi": np.nan,
"effective_suppliers":
np.nan,
"supplier_count": 0,
}
hhi = (
shares ** 2
).sum()
return {
"cr1":
shares
.nlargest(1)
.sum(),
"cr3":
shares
.nlargest(3)
.sum(),
"cr5":
shares
.nlargest(5)
.sum(),
"hhi":
hhi,
"effective_suppliers":
(
1 / hhi
if hhi > 0
else np.nan
),
"supplier_count":
int(
(
values > 0
).sum()
),
}
now = calc_one(
current_share,
current_values,
current_total,
)
before = calc_one(
previous_share,
previous_values,
previous_total,
)
# Total Variation Distance
# 0 = 構造変化なし
# 1 = 完全に別の供給構造
if (
current_total > 0
and previous_total > 0
):
structure_change = (
0.5
*
(
current_share
- previous_share
)
.abs()
.sum()
)
else:
structure_change = np.nan
return {
"basis":
prefix,
"cr1_current":
now["cr1"],
"cr1_yoy_base":
before["cr1"],
"cr1_delta_pp":
(
(
now["cr1"]
- before["cr1"]
)
* 100
if (
pd.notna(
now["cr1"]
)
and
pd.notna(
before["cr1"]
)
)
else np.nan
),
"cr3_current":
now["cr3"],
"cr3_yoy_base":
before["cr3"],
"cr3_delta_pp":
(
(
now["cr3"]
- before["cr3"]
)
* 100
if (
pd.notna(
now["cr3"]
)
and
pd.notna(
before["cr3"]
)
)
else np.nan
),
"cr5_current":
now["cr5"],
"cr5_yoy_base":
before["cr5"],
"cr5_delta_pp":
(
(
now["cr5"]
- before["cr5"]
)
* 100
if (
pd.notna(
now["cr5"]
)
and
pd.notna(
before["cr5"]
)
)
else np.nan
),
"hhi_current":
now["hhi"],
"hhi_yoy_base":
before["hhi"],
"hhi_delta":
(
now["hhi"]
- before["hhi"]
if (
pd.notna(
now["hhi"]
)
and
pd.notna(
before["hhi"]
)
)
else np.nan
),
"effective_suppliers_current":
now[
"effective_suppliers"
],
"effective_suppliers_yoy_base":
before[
"effective_suppliers"
],
"supplier_count_current":
now[
"supplier_count"
],
"supplier_count_yoy_base":
before[
"supplier_count"
],
"structure_change_index":
structure_change,
}
concentration_df = (
pd.DataFrame(
[
concentration("value"),
concentration("quantity"),
]
)
.set_index("basis")
)
# 元の国カラム名に戻す
country = country.rename(
columns={
"_country":
country_col
}
)
# =================================================
# 8. TOP N
# =================================================
country_top_value = (
country
.sort_values(
[
"value_current",
"value_yoy_base",
],
ascending=False
)
.head(top_n)
.reset_index(drop=True)
)
country_top_quantity = (
country
.sort_values(
[
"quantity_current",
"quantity_yoy_base",
],
ascending=False
)
.head(top_n)
.reset_index(drop=True)
)
# =================================================
# 9. 新規 / 消失国
# =================================================
events = (
country[
country["event_flag"]
]
.sort_values(
[
"status",
"value_current",
"value_yoy_base",
],
ascending=[
True,
False,
False,
]
)
.reset_index(drop=True)
)
country_all = (
country
.sort_values(
[
"value_current",
"value_yoy_base",
],
ascending=False
)
.reset_index(drop=True)
)
# =================================================
# Return
# =================================================
return {
"target_month":
str(target),
"yoy_month":
str(yoy_month),
"monthly":
monthly.reset_index(),
"metric_summary":
metric_summary,
"concentration":
concentration_df,
"country_all":
country_all,
"country_top_value":
country_top_value,
"country_top_quantity":
country_top_quantity,
"events":
events,
"warnings":
warnings,
}