Spaces:
Sleeping

Corin1998 commited on
Commit
7e7bb35
·
verified ·
1 Parent(s): 690d599

Update app/scoring.py

Browse files
Files changed (1) hide show
  1. app/scoring.py +25 -533
app/scoring.py CHANGED
@@ -1,535 +1,27 @@
 
1
  from __future__ import annotations
2
- from typing import Dict, Any, List, Tuple
3
- import math
4
  import pandas as pd
5
-
6
- # app/scoring.py の先頭付近
7
-
8
- __all__ = [
9
- # 既存のエクスポートに加えて…
10
- "get_external_template_df",
11
- "fill_missing_with_external", # ← これを追加
12
- "score_external_from_df",
13
- "ai_score_company",
14
- "hybrid_score",
15
- "make_summary",
16
- ]
17
-
18
-
19
- def fill_missing_with_external(df: pd.DataFrame, company: str, country: str) -> pd.DataFrame:
20
- """
21
- 外部情報による欠損補完(未実装でも UI が落ちないようにノーオペで返す)。
22
- 後から外部推定ロジックを入れるならここに実装を追加。
23
- """
24
- return df.copy()
25
-
26
-
27
- # ========== 入力テンプレ(外部評価で使う項目の最小集合・欠損は中立処理) ==========
28
- def get_external_template_df() -> pd.DataFrame:
29
- rows = [
30
- ("経営者能力","予実達成率_3年平均(%)"),
31
- ("経営者能力","監査・内部統制の重大な不備 件数(過去3年)"),
32
- ("経営者能力","重大コンプライアンス件数(過去3年)"),
33
- ("経営者能力","社外取締役比率(%)"),
34
- ("経営者能力","代表者の業界経験年数"),
35
- ("経営者能力","現預金(円)"),
36
- ("経営者能力","月商(円)"),
37
- ("経営者能力","担保余力評価額(円)"),
38
- ("経営者能力","倒産歴の有無(TRUE/FALSE)"),
39
- ("経営者能力","倒産からの経過年数"),
40
- ("経営者能力","重大事件・事故件数(過去10年)"),
41
- ("成長率","売上_期3(最新期)"),
42
- ("成長率","売上_期2"),
43
- ("成長率","売上_期1(最古期)"),
44
- ("成長率","営業利益_期3(最新期)"),
45
- ("成長率","営業利益_期2"),
46
- ("成長率","営業利益_期1(最古期)"),
47
- ("成長率","主力商品数"),
48
- ("成長率","成長中主力商品数"),
49
- ("安定性","自己資本比率(%)"),
50
- ("安定性","利益剰余金(円)"),
51
- ("安定性","支払遅延件数(直近12ヶ月)"),
52
- ("安定性","不渡り件数(直近12ヶ月)"),
53
- ("安定性","平均支払遅延日数"),
54
- ("安定性","メインバンク明確か(TRUE/FALSE)"),
55
- ("安定性","借入先数"),
56
- ("安定性","メインバンク借入シェア(%)"),
57
- ("安定性","コミットメントライン等の長期与信枠あり(TRUE/FALSE)"),
58
- ("安定性","担保余力評価額(円)"),
59
- ("安定性","月商(円)_再掲"),
60
- ("安定性","主要顧客上位1社売上比率(%)"),
61
- ("安定性","主要顧客上位3社売上比率(%)"),
62
- ("安定性","主要顧客の平均信用スコア(0-100)"),
63
- ("安定性","不良債権件数(直近12ヶ月)"),
64
- ("安定性","業歴(年)"),
65
- ("公平性・総合世評","有価証券報告書提出企業か(TRUE/FALSE)"),
66
- ("公平性・総合世評","決算公告や官報での公開あり(TRUE/FALSE)"),
67
- ("公平性・総合世評","HP/IRサイトで財務資料公開あり(TRUE/FALSE)"),
68
- ("公平性・総合世評","直近更新が定め通りか(TRUE/FALSE)"),
69
- ("業務効率","従業員数"),
70
- ("業務効率","従業員1人当たり売上(円)"),
71
- ("業務効率","従業員1人当たり純利益(円)"),
72
- ("業務効率","DSO(売掛回収日数)"),
73
- ("業務効率","DIO(在庫回転日数)"),
74
- ("業務効率","DPO(買掛支払日数)"),
75
- ("業務効率","流動比率"),
76
- ("業務効率","当座比率"),
77
- ]
78
- return pd.DataFrame([(c,i,"") for c,i in rows], columns=["カテゴリー","入力項目","値"])
79
-
80
- # ========== ユーティリティ ==========
81
- def _ref(df: pd.DataFrame, label: str):
82
- m = df["入力項目"].eq(label)
83
- if not m.any(): return None
84
- v = df.loc[m, "値"].values[0]
85
- if isinstance(v, str): v = v.strip()
86
- return v
87
-
88
- def _to_float(x, default=None):
89
- if x is None: return default
90
- if isinstance(x, (int,float)): return float(x)
91
- s = str(x).strip().replace(",","")
92
- if s=="" or s.lower() in ("nan","none"): return default
93
- try: return float(s)
94
- except: return default
95
-
96
- def _to_bool(x, default=None):
97
- if x is None: return default
98
- if isinstance(x, bool): return x
99
- s=str(x).strip().lower()
100
- if s in ("true","t","1","yes","y","有","あり"): return True
101
- if s in ("false","f","0","no","n","無","なし"): return False
102
- return default
103
-
104
- def _clamp(v, lo, hi): return max(lo, min(hi, v))
105
- def _ratio(a,b):
106
- if a is None or b is None or b==0: return None
107
- return a/b
108
- def _lin(x,x0,x1,y0,y1):
109
- if x<=x0: return y0
110
- if x>=x1: return y1
111
- return y0+(y1-y0)*(x-x0)/(x1-x0)
112
- def _ramp(x, good, bad, lo=0.0, hi=10.0, neutral=None):
113
- if x is None: return (neutral if neutral is not None else (hi+lo)/2)
114
- return _clamp(_lin(x, bad, good, lo, hi) if good>bad else _lin(x, good, bad, hi, lo), lo, hi)
115
-
116
- # ========== 外部評価の重み(合計は自動正規化) ==========
117
- _WEIGHTS = {
118
- ("経営者能力","経営姿勢"): 8,
119
- ("経営者能力","事業経験"): 5,
120
- ("経営者能力","資産担保力"): 6,
121
- ("経営者能力","減点事項"): 7,
122
- ("成長率","売上高伸長性"): 10,
123
- ("成長率","利益伸長性"): 10,
124
- ("成長率","商品"): 6,
125
- ("安定性","自己資本"): 8,
126
- ("安定性","決済振り"): 10,
127
- ("安定性","金融取引"): 6,
128
- ("安定性","資産担保余力"): 6,
129
- ("安定性","取引先"): 6,
130
- ("安定性","業歴"): 4,
131
- ("公平性・総合世評","ディスクロージャー"): 8,
132
- # 新設:業務効率
133
- ("業務効率","従業員効率"): 6,
134
- ("業務効率","回転日数/運転資本"): 6,
135
- ("業務効率","流動性"): 4,
136
- }
137
- _WEIGHT_NORM = 100.0 / float(sum(_WEIGHTS.values()))
138
-
139
- def _add(items, cat, name, raw, weight, reason):
140
- contrib = round((raw/10.0)*weight*_WEIGHT_NORM, 2)
141
- items.append({
142
- "category": cat, "name": name,
143
- "raw": round(raw,2), "weight": round(weight*_WEIGHT_NORM,2),
144
- "score": contrib, "reason": reason
145
- })
146
-
147
- # ========== 外部評価 ==========
148
- def score_external_from_df(df: pd.DataFrame) -> Dict[str, Any]:
149
- items: List[Dict[str, Any]] = []
150
-
151
- # 経営者能力周り
152
- yoy3 = _to_float(_ref(df,"予実達成率_3年平均(%)"))
153
- audit_bad = _to_float(_ref(df,"監査・内部統制の重大な不備 件数(過去3年)"))
154
- comp_bad = _to_float(_ref(df,"重大コンプライアンス件数(過去3年)"))
155
- indep = _to_float(_ref(df,"社外取締役比率(%)"))
156
- exp_years = _to_float(_ref(df,"代表者の業界経験年数"))
157
- cash = _to_float(_ref(df,"現預金(円)"))
158
- ms = _to_float(_ref(df,"月商(円)"))
159
- coll = _to_float(_ref(df,"担保余力評価額(円)"))
160
- has_bk = _to_bool(_ref(df,"倒産歴の有無(TRUE/FALSE)"))
161
- bk_years = _to_float(_ref(df,"倒産からの経過年数"))
162
- incidents = _to_float(_ref(df,"重大事件・事故件数(過去10年)"))
163
-
164
- # 成長
165
- s3=_to_float(_ref(df,"売上_期3(最新期)")); s2=_to_float(_ref(df,"売上_期2")); s1=_to_float(_ref(df,"売上_期1(最古期)"))
166
- p3=_to_float(_ref(df,"営業利益_期3(最新期)")); p2=_to_float(_ref(df,"営業利益_期2")); p1=_to_float(_ref(df,"営業利益_期1(最古期)"))
167
- prod_n=_to_float(_ref(df,"主力商品数")); prod_g=_to_float(_ref(df,"成長中主力商品数"))
168
-
169
- # 安定
170
- equity=_to_float(_ref(df,"自己資本比率(%)"))
171
- delay_cnt=_to_float(_ref(df,"支払遅延件数(直近12ヶ月)")); boun_cnt=_to_float(_ref(df,"不渡り件数(直近12ヶ月)"))
172
- delay_days=_to_float(_ref(df,"平均支払遅延日数"))
173
- mainbank=_to_bool(_ref(df,"メインバンク明確か(TRUE/FALSE)"))
174
- lenders=_to_float(_ref(df,"借入先数")); main_share=_to_float(_ref(df,"メインバンク借入シェア(%)"))
175
- has_line=_to_bool(_ref(df,"コミットメントライン等の長期与信枠あり(TRUE/FALSE)"))
176
- coll2=_to_float(_ref(df,"担保余力評価額(円)")); ms2=_to_float(_ref(df,"月商(円)_再掲")) or ms
177
- top1=_to_float(_ref(df,"主要顧客上位1社売上比率(%)")); cust_score=_to_float(_ref(df,"主要顧客の平均信用スコア(0-100)"))
178
- npl=_to_float(_ref(df,"不良債権件数(直近12ヶ月)"))
179
- years=_to_float(_ref(df,"業歴(年)"))
180
-
181
- # 公平性
182
- has_sec=_to_bool(_ref(df,"有価証券報告書提出企業か(TRUE/FALSE)"))
183
- pub_off=_to_bool(_ref(df,"決算公告や官報での公開あり(TRUE/FALSE)"))
184
- pub_web=_to_bool(_ref(df,"HP/IRサイトで財務資料公開あり(TRUE/FALSE)"))
185
- upd_on=_to_bool(_ref(df,"直近更新が定め通りか(TRUE/FALSE)"))
186
-
187
- # 効率(任意追加)
188
- emp = _to_float(_ref(df,"従業員数"))
189
- rev_per_emp=_to_float(_ref(df,"従業員1人当たり売上(円)"))
190
- ni_per_emp=_to_float(_ref(df,"従業員1人当たり純利益(円)"))
191
- dso=_to_float(_ref(df,"DSO(売掛回収日数)"))
192
- dio=_to_float(_ref(df,"DIO(在庫回転日数)"))
193
- dpo=_to_float(_ref(df,"DPO(買掛支払日数)"))
194
- curr=_to_float(_ref(df,"流動比率")); quick=_to_float(_ref(df,"当座比率"))
195
-
196
- # 派生
197
- def cagr(a,b):
198
- if a and b and a>0:
199
- try: return (b/a)**(1/2)-1.0
200
- except: return None
201
- return None
202
- s_cagr = cagr(s1,s3); p_cagr = cagr(p1,p3)
203
- cash_ms = _ratio(cash, ms or ms2)
204
- coll_ms = _ratio(coll2 or coll, ms2 or ms)
205
-
206
- # 経営者能力
207
- s_att1=_ramp(yoy3, 90, 50)
208
- s_att2=_ramp(0 if audit_bad is None else -audit_bad, 0, -3)
209
- s_att3=_ramp(0 if comp_bad is None else -comp_bad, 0, -2)
210
- s_att4=_ramp(indep, 33, 0)
211
- mg_att=(s_att1+s_att2+s_att3+s_att4)/4.0
212
- _add(items,"経営者能力","経営姿勢", mg_att, _WEIGHTS[("経営者能力","経営姿勢")],
213
- f"予実{yoy3 or '—'}%/監査{audit_bad or 0}/違反{comp_bad or 0}/社外{indep or '��'}%")
214
- mg_exp=_ramp(exp_years if exp_years is not None else 5.0, 15, 0)
215
- _add(items,"経営者能力","事業経験", mg_exp, _WEIGHTS[("経営者能力","事業経験")],
216
- f"業界経験{exp_years if exp_years is not None else '不明→中立'}年")
217
- mg_asset=_ramp(cash_ms, 1.5, 0.2)
218
- _add(items,"経営者能力","資産担保力", mg_asset, _WEIGHTS[("経営者能力","資産担保力")],
219
- f"現預金/月商≈{round(cash_ms,2) if cash_ms is not None else '—'}")
220
- if incidents and incidents>0:
221
- pen=0.0; rs=f"重大事故{int(incidents)}件"
222
- elif has_bk:
223
- if bk_years and bk_years>=10: pen=6.0; rs=f"倒産歴あり({int(bk_years)}年)軽減"
224
- else: pen=3.0; rs="倒産歴あり"
225
- else:
226
- pen=10.0; rs="事故/倒産歴なし"
227
- _add(items,"経営者能力","減点事項", pen, _WEIGHTS[("経営者能力","減点事項")], rs)
228
-
229
- # 成長率
230
- _add(items,"成長率","売上高伸長性", _ramp(s_cagr, 0.10, -0.05), _WEIGHTS[("成長率","売上高伸長性")],
231
- f"CAGR売上≈{round((s_cagr or 0)*100,1)}%")
232
- _add(items,"成長率","利益伸長性", _ramp(p_cagr, 0.12, -0.05), _WEIGHTS[("成長率","利益伸長性")],
233
- f"CAGR利益≈{round((p_cagr or 0)*100,1)}%")
234
- if prod_n is None and prod_g is None:
235
- gr_prod=5.0; r="不明→中立"
236
- else:
237
- prod_n=max(min(prod_n or 0, 20),0); prod_g=max(min(prod_g or 0, 20),0)
238
- ratio=_ratio(prod_g, prod_n if prod_n>0 else None)
239
- gr_prod=_ramp(ratio, 0.7, 0.0); r=f"主力{int(prod_n)}/成長{int(prod_g)}(比率{round(ratio or 0,2)})"
240
- _add(items,"成長率","商品", gr_prod, _WEIGHTS[("成長率","商品")], r)
241
-
242
- # 安定性
243
- _add(items,"安定性","自己資本", _ramp(equity, 40, 5), _WEIGHTS[("安定性","自己資本")],
244
- f"自己資本比率{equity or '—'}%")
245
- if (delay_cnt is not None) or (boun_cnt is not None) or (delay_days is not None):
246
- d_cnt=max(min(delay_cnt or 0,12),0)
247
- b_cnt=max(min(boun_cnt or 0,3),0)
248
- d_days=max(min(delay_days or 0,60),0)
249
- sc=( _ramp(-d_cnt,0,-6)+_ramp(-b_cnt,0,-1)+_ramp(-d_days,0,-30) )/3.0
250
- rs=f"遅延{int(d_cnt)}/不渡{int(b_cnt)}/平均{int(d_days)}日"
251
- else:
252
- sc=_ramp(cash_ms, 1.0, 0.2); rs=f"代替推定(現預金/月商≈{round(cash_ms or 0,2)})"
253
- _add(items,"安定性","決済振り", sc, _WEIGHTS[("安定性","決済振り")], rs)
254
- sc_mb=5.0; parts=[]
255
- if mainbank is not None: sc_mb+=2.0 if mainbank else -1.0; parts.append(f"メイン{'有' if mainbank else '無'}")
256
- if has_line is not None: sc_mb+=1.5 if has_line else 0; parts.append(f"枠{'有' if has_line else '無'}")
257
- if lenders is not None: sc_mb+=_ramp(lenders,3,0,lo=0,hi=2); parts.append(f"借入先{int(lenders)}")
258
- if main_share is not None: sc_mb+=1.0 if 30<=main_share<=70 else -0.5; parts.append(f"メイン比率{int(main_share)}%")
259
- _add(items,"安定性","金融取引", _clamp(sc_mb,0,10), _WEIGHTS[("安定性","金融取引")], " / ".join(parts) or "情報不足")
260
- _add(items,"安定性","資産担保余力", _ramp(coll_ms, 4.0, 0.0), _WEIGHTS[("安定性","資産担保余力")],
261
- f"担保余力/月商≈{round(coll_ms or 0,2)}")
262
- cust=( _ramp(-(top1 if top1 is not None else 50),0,-80)+ _ramp(cust_score,80,50)+ _ramp(-(npl or 1),0,-3) )/3.0
263
- _add(items,"安定性","取引先", cust, _WEIGHTS[("安定性","取引先")],
264
- f"上位1社{top1 or '—'}%/信用{cust_score or '—'}/不良{int(npl or 0)}")
265
- _add(items,"安定性","業歴", _ramp(years, 20, 1), _WEIGHTS[("安定性","業歴")], f"{years or '—'}年")
266
-
267
- # 公平性
268
- sc_dis=0.0; parts=[]
269
- if has_sec: sc_dis=10.0; parts.append("有報")
270
- elif (pub_off or pub_web):
271
- sc_dis=8.0; parts.append("公開あり")
272
- if upd_on: sc_dis+=1.0; parts.append("更新遵守")
273
- else:
274
- sc_dis=4.0; parts.append("公開乏しい")
275
- _add(items,"公平性・総合世評","ディスクロージャー", _clamp(sc_dis,0,10), _WEIGHTS[("公平性・総合世評","ディスクロージャー")], " / ".join(parts))
276
-
277
- # 業務効率(新設)
278
- eff_emp = ( _ramp(_ratio(rev_per_emp, 100_000_000), 2.0, 0.3) + _ramp(_ratio(ni_per_emp, 10_000_000), 1.5, 0.1) )/2.0 \
279
- if (rev_per_emp or ni_per_emp) else 5.0
280
- _add(items,"業務効率","従業員効率", eff_emp, _WEIGHTS[("業務効率","従業員効率")],
281
- f"売上/人 {int(rev_per_emp or 0):,} / 純益/人 {int(ni_per_emp or 0):,}")
282
- wc = []
283
- if dso is not None: wc.append(_ramp(-dso, -40, -120))
284
- if dio is not None: wc.append(_ramp(-dio, -60, -180))
285
- if dpo is not None: wc.append(_ramp(dpo, 90, 10))
286
- eff_wc = sum(wc)/len(wc) if wc else 5.0
287
- _add(items,"業務効率","回転日数/運転資本", eff_wc, _WEIGHTS[("業務効率","回転日数/運転資本")],
288
- f"DSO {dso or '—'}/ DIO {dio or '—'}/ DPO {dpo or '—'}")
289
- liq = ( _ramp(curr, 2.0, 1.0) + _ramp(quick, 1.5, 0.7) )/2.0 if (curr or quick) else 5.0
290
- _add(items,"業務効率","流動性", liq, _WEIGHTS[("業務効率","流動性")],
291
- f"CR {round(curr or 0,2)}/ QR {round(quick or 0,2)}")
292
-
293
- total = round(sum(x["score"] for x in items), 1)
294
- return {"external_total": total, "items": items,
295
- "notes": "欠損は中立点、金額は比率化/クリップ、連続スコア化+重みは自動正規化(合計100)。"}
296
- # ========== AIスコア ==========
297
- # --- app/scoring.py の中(他は既存のまま) ---
298
-
299
- def ai_score_company(
300
- meta: Dict[str, Any] | None = None,
301
- fin: Dict[str, Any] | None = None,
302
- indicators: Dict[str, float] | None = None,
303
- website_text: str | None = None,
304
- ) -> Dict[str, Any]:
305
- """
306
- より柔軟な AI 評価:
307
- - 業界(成長/成熟/逆風)
308
- - 企業規模(売上)
309
- - 成長性(売上CAGR)
310
- - 収益性(営業/純利益率、EBITDA率)
311
- - 財務健全性(自己資本比率/流動比率/金利負担)
312
- - 効率性(総資産回転率、CCC)
313
- - 従業員生産性(売上/人、純利益/人)
314
- - ディスクロージャ/データ充足度
315
- - (任意)Webサイトの定性的ヒント
316
- を 0–10 点にスケールし、重み付きで 0–100 に統合。
317
- """
318
- meta = meta or {}
319
- ind = indicators or {}
320
- P = (fin or {}).get("periods") or []
321
-
322
- def g0(k): # 最新期
323
- return P[0].get(k) if P else None
324
-
325
- # ------------- ユーティリティ -------------
326
- def _cagr(v_old, v_new, years: float = 2.0):
327
- if v_old is None or v_new is None or v_old <= 0: return None
328
- try: return (float(v_new) / float(v_old)) ** (1.0 / years) - 1.0
329
- except Exception: return None
330
-
331
- def _nz(x, default=None): # None→default
332
- return default if x is None else x
333
-
334
- # ------------- 指数化ヘルパ(既存ロジックを活用) -------------
335
- # good側が満点、bad側が0点、線形。欠損は5点(中立)。
336
- def ramp(x, good, bad, lo=0.0, hi=10.0, neutral=5.0):
337
- if x is None: return neutral
338
- if good > bad:
339
- return _clamp(_lin(x, bad, good, lo, hi), lo, hi)
340
- else:
341
- return _clamp(_lin(x, good, bad, hi, lo), lo, hi)
342
-
343
- # ====== 各サブスコア(0–10) ======
344
- # 業界アトラクトiveness
345
- industry = (meta.get("industry") or "").lower()
346
- industry_map_pos = ["saas","ai","半導体","半導體","再エネ","再生可能","医薬","バイオ","fintech","it","ソフト"]
347
- industry_map_neg = ["成熟","構造不況","縮小","紙・印刷","衰退","石炭","たばこ"]
348
- ind_score = 5.0
349
- if any(k in industry for k in industry_map_pos):
350
- ind_score = 7.5
351
- if "ai" in industry or "saas" in industry: ind_score = 8.5
352
- if any(k in industry for k in industry_map_neg):
353
- ind_score = min(ind_score, 4.0)
354
-
355
- # 規模(売上)
356
- revenue = g0("revenue")
357
- size_score = ramp(revenue, good=50_000_000_000, bad=100_000_000) # 50億〜5000億で調整可
358
-
359
- # 成長性(売上CAGR:期1→期3があれば)
360
- rev_old = P[2].get("revenue") if len(P) >= 3 else None
361
- growth = _cagr(rev_old, revenue, years=2.0)
362
- growth_score = ramp(growth, good=0.15, bad=-0.05)
363
-
364
- # 収益性
365
- opm = ind.get("operating_margin")
366
- npm = ind.get("net_margin")
367
- ebitda_m = ind.get("ebitda_margin")
368
- prof_score = (ramp(opm, 0.15, 0.01) + ramp(npm, 0.10, 0.00) + ramp(ebitda_m, 0.20, 0.05)) / 3.0
369
-
370
- # 財務健全性
371
- eq_ratio = ind.get("equity_ratio")
372
- cur_ratio = ind.get("current_ratio")
373
- icr = ind.get("interest_coverage")
374
- fin_score = (ramp(eq_ratio, 0.40, 0.05) + ramp(cur_ratio, 1.5, 0.8) + ramp(icr, 10.0, 1.0)) / 3.0
375
-
376
- # 効率性(総資産回転+CCC)
377
- tat = ind.get("total_asset_turnover")
378
- dso = ind.get("dso_days"); dio = ind.get("dio_days"); dpo = ind.get("dpo_days")
379
- ccc = None
380
- if dso is not None or dio is not None or dpo is not None:
381
- ccc = _nz(dso, 60.0) + _nz(dio, 45.0) - _nz(dpo, 45.0)
382
- eff_score = (ramp(tat, 1.5, 0.5) + ramp(-ccc if ccc is not None else None, good=0, bad=-150)) / 2.0
383
-
384
- # 従業員生産性
385
- # (fin.parsers で計算済ならそれを使い、無ければ簡易推定)
386
- rev_per_emp = ind.get("revenue_per_emp")
387
- ni_per_emp = ind.get("net_income_per_emp")
388
- if rev_per_emp is None and fin and (fin.get("company") or {}).get("employees"):
389
- emp = fin["company"]["employees"]
390
- if emp and revenue: rev_per_emp = float(revenue) / float(emp)
391
- if emp and g0("net_income") is not None: ni_per_emp = float(g0("net_income") or 0) / float(emp)
392
- prod_score = (ramp(rev_per_emp, 30_000_000, 8_000_000) + ramp(ni_per_emp, 2_000_000, 0)) / 2.0
393
-
394
- # データ充足/ディスクロージャ
395
- filled = 0
396
- if P:
397
- for k in ("revenue","operating_income","net_income","total_assets","net_assets","current_assets","current_liabilities"):
398
- filled += 1 if g0(k) is not None else 0
399
- disclosure_score = 3.0 + min(7.0, filled) * 1.0 # 3〜10点
400
-
401
- # (任意)Webサイトの定性的ヒント
402
- web_score = 5.0
403
- if website_text:
404
- txt = website_text.lower()
405
- pos_kw = ["ai","machine learning","saas","subscription","esg","sustainab","iso9001","iso27001","patent","特許","研究開発","rd","export","global","海外展開","soc2"]
406
- neg_kw = ["リコール","不祥事","粉飾","遅延","訴訟","倒産","債務超過"]
407
- web_score += 2.0 * sum(1 for k in pos_kw if k in txt)
408
- web_score -= 3.0 * sum(1 for k in neg_kw if k in txt)
409
- web_score = _clamp(web_score, 0, 10)
410
-
411
- # ====== 重み付け(合計100) ======
412
- weights = {
413
- "Industry": 18, "Scale": 10, "Growth": 15, "Profitability": 15,
414
- "Financial": 12, "Efficiency": 10, "Productivity": 8,
415
- "Disclosure": 5, "QualitativeWeb": 7,
416
- }
417
- raw = {
418
- "Industry": ind_score,
419
- "Scale": size_score,
420
- "Growth": growth_score,
421
- "Profitability": prof_score,
422
- "Financial": fin_score,
423
- "Efficiency": eff_score,
424
- "Productivity": prod_score,
425
- "Disclosure": disclosure_score,
426
- "QualitativeWeb": web_score,
427
- }
428
- total = 0.0
429
- breakdown = []
430
- for k, w in weights.items():
431
- part = (raw[k] / 10.0) * w
432
- breakdown.append({"name": k, "raw_0to10": round(raw[k],2), "weight": w, "contribution": round(part,2)})
433
- total += part
434
- ai_total = round(_clamp(total, 0, 100), 1)
435
-
436
- # 文章サマリ(読みやすく)
437
- bullets = []
438
- if growth is not None: bullets.append(f"売上CAGR {growth*100:.1f}%")
439
- if opm is not None: bullets.append(f"営業利益率 {opm*100:.1f}%")
440
- if eq_ratio is not None: bullets.append(f"自己資本比率 {eq_ratio*100:.1f}%")
441
- if cur_ratio is not None: bullets.append(f"流動比率 {cur_ratio:.2f}倍")
442
- if tat is not None: bullets.append(f"総資産回転率 {tat:.2f}回")
443
- if ccc is not None: bullets.append(f"CCC 約{ccc:.0f}日(短いほど良)")
444
- if rev_per_emp is not None: bullets.append(f"1人当たり売上 {int(rev_per_emp):,}円")
445
- if ni_per_emp is not None: bullets.append(f"1人当たり純利益 {int(ni_per_emp):,}円")
446
-
447
- qual = []
448
- if website_text:
449
- if web_score >= 7: qual.append("Web情報から成長性/信頼性の示唆あり")
450
- if web_score <= 3: qual.append("Web情報に留意点あり")
451
- narrative = f"AI評価は **{ai_total} 点**。主要指標:{(' / '.join(bullets) or '—')}。"
452
- if industry:
453
- narrative += f" 業種は「{industry}」。"
454
- if qual:
455
- narrative += " 定性的所見:" + "・".join(qual) + "。"
456
-
457
- return {
458
- "ai_total": ai_total,
459
- "factors": breakdown,
460
- "notes": "業界・規模・成長・収益性・健全性・効率・生産性・開示・Web定性を統合。",
461
- "narrative": narrative,
462
- }
463
-
464
-
465
-
466
- # ========== ハイブリッド ==========
467
- def hybrid_score(ext: Dict[str, Any], ai: Dict[str, Any], w_pdf=0.5, w_ai=0.5) -> Dict[str, Any]:
468
- w_pdf=_clamp(w_pdf,0,1); w_ai=_clamp(w_ai,0,1)
469
- if w_pdf+w_ai==0: w_pdf=w_ai=0.5
470
- return {"hybrid_total": round((ext["external_total"]*w_pdf + ai["ai_total"]*w_ai)/(w_pdf+w_ai),1),
471
- "weights":{"w_pdf":w_pdf,"w_ai":w_ai}}
472
-
473
- # ========== 総評 ==========
474
- def make_summary(name: str, ext: Dict[str, Any], ai: Dict[str, Any], hyb: Dict[str, Any]) -> str:
475
- """総評(外部・AI・ハイブリッドをまとめ、AIの文章サマリを付与)"""
476
- def pick(cat, nm):
477
- for it in ext.get("items", []):
478
- if it["category"] == cat and it["name"] == nm: return it
479
- return None
480
- mg = pick("経営者能力", "資産担保力")
481
- st = pick("安定性", "決済振り")
482
- gr = pick("成長率", "売上高伸長性")
483
-
484
- parts = []
485
- title = f"**{name or '対象企業'}** は 外部 {ext['external_total']} 点 / AI {ai['ai_total']} 点 / ハイブリッド {hyb['hybrid_total']} 点。"
486
- parts.append(title)
487
- if gr: parts.append(f"売上伸長性 raw {gr['raw']:.1f}/10({gr['reason']})。")
488
- if st: parts.append(f"資金繰り・支払ぶり raw {st['raw']:.1f}/10({st['reason']})。")
489
- if mg: parts.append(f"現預金対月商余力 raw {mg['raw']:.1f}/10({mg['reason']})。")
490
- # AIの文章サマリを最後に追加
491
- if ai.get("narrative"):
492
- parts.append("")
493
- parts.append(ai["narrative"])
494
- parts.append("")
495
- parts.append("※ 追加情報(流動比率・ICR・固定長期適合など)が揃うほど推定精度が向上します。")
496
- return "\n".join(parts)
497
-
498
- # ========== 与信/融資/投資(独立評価) ==========
499
- def assess_credit(ext: Dict[str, Any], fin_ratios: Dict[str, Any]) -> Dict[str, Any]:
500
- score = ext["external_total"]
501
- cr = fin_ratios.get("current_ratio") or 1.5
502
- dso = fin_ratios.get("dso_days") or 60
503
- band = "A" if score>=75 else "B" if score>=60 else "C" if score>=45 else "D"
504
- suggested_terms = {
505
- "site_days": 30 if dso<=60 else 45 if dso<=90 else 60,
506
- "review_cycle": "月次" if band in ("C","D") else "四半期"
507
- }
508
- # 限度額(目安):月商×(0.8〜1.5)をスコアでチューニング
509
- factor = 1.5 if band=="A" else 1.2 if band=="B" else 0.9 if band=="C" else 0.6
510
- return {"credit_band": band, "credit_score": round(score,1), "suggested_terms": suggested_terms,
511
- "limit_formula":"月商×係数", "limit_factor": factor}
512
-
513
- def assess_loan(ext: Dict[str, Any], fin: Dict[str, Any], fin_ratios: Dict[str, Any]) -> Dict[str, Any]:
514
- score = ext["external_total"]
515
- band = "AA" if score>=80 else "A" if score>=70 else "BBB" if score>=60 else "BB" if score>=50 else "B"
516
- cr = fin_ratios.get("current_ratio") or 1.5
517
- # 限度額(目安):営業CF×年数 + 担保余力の一部
518
- latest = (fin.get("periods") or [{}])[0]
519
- ocf = latest.get("operating_cf") or 0
520
- coll = latest.get("cash_and_equivalents") or 0
521
- max_amt = max(0, (ocf*3) + (coll*0.5))
522
- tenure = 5 if band in ("AA","A") else 3
523
- return {"loan_band": band, "loan_score": round(score,1), "loan_limit_estimate": int(max_amt),
524
- "suggested_tenor_years": tenure, "notes":"返済財源は営業CF重視。"}
525
-
526
- def assess_investment(ai: Dict[str, Any], fin: Dict[str, Any], ext: Dict[str, Any]) -> Dict[str, Any]:
527
- ai_s = ai["ai_total"]; ex_s = ext["external_total"]
528
- stance = "Buy" if (ai_s>=70 and ex_s>=60) else "Hold" if (ai_s>=55 and ex_s>=50) else "Avoid"
529
- # 超簡易の時価推定(目安):最新売上×(1.0〜2.5倍) を AI スコアでスケール
530
- latest = (fin.get("periods") or [{}])[0]
531
- rev = latest.get("revenue") or 0
532
- mult = 1.0 + (ai_s/100.0)*1.5
533
- est_mktcap = int(rev * mult)
534
- return {"investment_opinion": stance, "ai_bias": ai_s, "external_bias": ex_s,
535
- "estimated_market_cap": est_mktcap, "notes":"成長期待と基礎体力のバランスで判断。"}
 
1
+ # app/bridge_external.py
2
  from __future__ import annotations
 
 
3
  import pandas as pd
4
+ from typing import Dict, Any
5
+ from app.scoring import get_external_template_df, score_external_from_df
6
+
7
+ def figures_to_external_df(fig: Dict[str, Any]) -> pd.DataFrame:
8
+ df = get_external_template_df()
9
+ def setv(label, v):
10
+ m = df["入力項目"].eq(label)
11
+ if m.any():
12
+ df.loc[m, "値"] = ("" if v is None else v)
13
+ # 利用できる欄だけ埋める(欠損は scoring.py 側で中立点処理)
14
+ setv("現預金(円)", fig.get("cash"))
15
+ setv("月商(円)", fig.get("sales") and fig.get("sales")/12.0)
16
+ setv("自己資本比率(%)", fig.get("equity") and fig.get("total_assets") and 100.0*fig["equity"]/fig["total_assets"])
17
+ setv("利益剰余金(円)", None) # PDFから取りにくいので空
18
+ setv("借入先数", None)
19
+ setv("担保余力評価額(円)", None)
20
+ setv("主要顧客上位1社売上比率(%)", None)
21
+ setv("不良債権件数(直近12ヶ月)", None)
22
+ setv("業歴(年)", None)
23
+ return df
24
+
25
+ def external_from_figures(fig: Dict[str, Any]) -> Dict[str, Any]:
26
+ df = figures_to_external_df(fig)
27
+ return score_external_from_df(df)