Spaces:
Sleeping

Corin1998 commited on
Commit
3f1b152
·
verified ·
1 Parent(s): 6116cd3

Update core/ai_judgement.py

Browse files
Files changed (1) hide show
  1. core/ai_judgement.py +155 -92
core/ai_judgement.py CHANGED
@@ -1,111 +1,174 @@
1
  # core/ai_judgement.py
2
  from __future__ import annotations
3
  import os, json
4
- from typing import Dict, Any
5
  from openai import OpenAI
6
 
7
- OPENAI_MODEL = os.environ.get("OPENAI_TEXT_MODEL", "gpt-4o-mini")
8
 
9
  def _client() -> OpenAI:
10
- # httpxは0.27系を使用(requirementsで固定)
11
- import httpx
12
- if not httpx.__version__.startswith("0.27."):
13
- raise RuntimeError(f"httpx==0.27.x が必要です(現在: {httpx.__version__})")
14
  key = os.environ.get("OPENAI_API_KEY")
15
  if not key:
16
- raise RuntimeError("OPENAI_API_KEY が未設定です。")
17
- return OpenAI(api_key=key, timeout=60)
18
-
19
- # --- 外部入力のLLM補助(市場成長・主力商品等) ---
20
- _SUGGEST_SCHEMA = """
21
- 返答は必ず次のJSONだけ。値が不明な場合は null。
22
- {
23
- "売上_期1(最古期)": null,
24
- "売上_期2": null,
25
- "売上_期3(最新期)": null,
26
- "営業利益_期1(最古期)": null,
27
- "営業利益_期2": null,
28
- "営業利益_期3(最新期)": null,
29
- "主力商品数": null,
30
- "成長中主力商品数": null,
31
- "市場の年成長率(%)": null,
32
- "業歴(年)": null
33
- }
34
- """
35
 
36
- def suggest_external_fields(company: str, fin: Dict[str, Any]) -> Dict[str, Any]:
37
  """
38
- 会社名・抽出済みfin(JSON)から、外部評価の不足項目をLLMで推定(公開情報ベースの一般値)。
39
- ※確信できない値は null 指示
40
  """
41
- c = _client()
42
- user = f"""次の会社の一般的な事業内容・市場動向を踏まえ、{_SUGGEST_SCHEMA}
43
- 会社名: {company or fin.get('company',{}).get('name','')}
44
- 抽出済み財務データの抜粋: {json.dumps(fin, ensure_ascii=False)[:1500]}"""
45
- resp = c.chat.completions.create(
46
- model=OPENAI_MODEL,
47
- messages=[
48
- {"role":"system","content":"あなたは客観的で慎重なアナリストです。推測が強い値は必ず null にすること。"},
49
- {"role":"user","content":user}
50
- ],
51
- temperature=0.2,
52
- response_format={"type":"json_object"},
53
- )
54
  try:
55
- return json.loads(resp.choices[0].message.content)
56
- except Exception:
57
- return {}
58
 
59
- # --- AI評価(外部評価と評価基準を分離) ---
60
- _AI_SCHEMA = """
61
- 返答は必ず次のJSONのみ:
62
- {
63
- "ai_score": 0, // 0-100 の総合スコア(外部評価と別基準)
64
- "subscores": {
65
- "収益性": 0, // 営業利益率・粗利/売上成長の質
66
- "健全性": 0, // レバレッジ、自己資本、CF一貫性
67
- "効率性": 0, // 営業CF/売上、在庫・債権推定の妥当性
68
- "市場適合": 0 // 市場成長×プロダクト強度(外部評価と重複しない観点で)
69
- },
70
- "memo_md": "..." // 箇条書きで、良い点・懸念・総評(客観・中立、誇張禁止)
71
- }
72
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
 
74
- def make_ai_memo(company: str, fin: Dict[str, Any], external_summary: Dict[str, Any]) -> Dict[str, Any]:
75
  """
76
- 外部評価(定量)とは別の観点で、LLMにより総合評価と短評を作成。
77
- - 外部評価が重視した「予実・与信・公開性」などは参照するが、AI評価は
78
- 収益性/健全性/効率性/市場適合の4本柱で別軸に採点。
79
  """
80
- c = _client()
81
- prompt = f"""以下のデータを読み、{_AI_SCHEMA}
82
- - 会社名: {company or fin.get('company',{}).get('name','')}
83
- - 抽出済み財務データ(単位は実数・円換算済み):
84
- {json.dumps(fin, ensure_ascii=False)[:2000]}
85
- - 外部評価(定量)の要約:
86
- {json.dumps(external_summary, ensure_ascii=False)[:1500]}
87
-
88
- 指針:
89
- - 客観・中立。憶測で断定しない。
90
- - 数値の根拠を短く触れる。
91
- - ai_score は subscores の平均±調整(顕著な矛盾がある時のみ±5pt以内)で0-100。
92
- - 表現は日本語、簡潔な箇条書き3×3+総評。
93
- """
94
- resp = c.chat.completions.create(
95
- model=OPENAI_MODEL,
96
- messages=[
97
- {"role":"system","content":"有能で公平な財務アナリスト。"},
98
- {"role":"user","content":prompt}
99
- ],
100
- temperature=0.3,
101
- response_format={"type":"json_object"},
102
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  try:
104
- data = json.loads(resp.choices[0].message.content)
105
- # 軽いバリデーション
106
- s = data.get("ai_score")
107
- if not isinstance(s, (int, float)):
108
- data["ai_score"] = 50
109
- return data
110
- except Exception as e:
111
- return {"ai_score": 50, "subscores":{}, "memo_md": f"AI評価の生成に失敗: {e}"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # core/ai_judgement.py
2
  from __future__ import annotations
3
  import os, json
4
+ from typing import Dict, Any, List
5
  from openai import OpenAI
6
 
7
+ OPENAI_MODEL_TEXT = os.environ.get("OPENAI_TEXT_MODEL", "gpt-4o-mini")
8
 
9
  def _client() -> OpenAI:
 
 
 
 
10
  key = os.environ.get("OPENAI_API_KEY")
11
  if not key:
12
+ raise RuntimeError("OPENAI_API_KEYが未設定です")
13
+ return OpenAI(api_key=key, timeout=30)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
+ def suggest_external_with_llm(fin: Dict[str, Any], company: str = "") -> Dict[str, Any]:
16
  """
17
+ 外部入力DFの不足をLLMが推定して埋めるための候補を返す。
18
+ ※ 失敗時は空dictで戻す(安全)
19
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  try:
21
+ prompt = f"""
22
+ あなたは企業アナリストです。以下の財務データから、可能な範囲で数値を推定して埋めてください。
23
+ 返答は必ず JSON オブジェクトのみで、存在しない項目は省略可。単位は以下のキーに合わせてください。
24
 
25
+ 必須候補キー例:
26
+ - "市場の年成長率(%)"
27
+ - "主力商品数"
28
+ - "成長中主力商品数"
29
+
30
+ [財務データ]
31
+ {json.dumps(fin, ensure_ascii=False)}
 
 
 
 
 
 
32
  """
33
+ cli = _client()
34
+ resp = cli.chat.completions.create(
35
+ model=OPENAI_MODEL_TEXT,
36
+ messages=[
37
+ {"role": "system", "content": "出力は厳密なJSON。説明不要。"},
38
+ {"role": "user", "content": prompt},
39
+ ],
40
+ response_format={"type": "json_object"},
41
+ temperature=0.2,
42
+ )
43
+ data = json.loads(resp.choices[0].message.content)
44
+ # 型の安全化
45
+ out = {}
46
+ for k in ["市場の年成長率(%)", "主力商品数", "成長中主力商品数"]:
47
+ v = data.get(k, None)
48
+ if v is None: continue
49
+ try:
50
+ out[k] = float(str(v).replace(",",""))
51
+ except Exception:
52
+ continue
53
+ # 整合性
54
+ if ("主力商品数" in out) and ("成長中主力商品数" in out):
55
+ if out["成長中主力商品数"] > out["主力商品数"]:
56
+ out["成長中主力商品数"] = out["主力商品数"]
57
+ return out
58
+ except Exception:
59
+ return {}
60
 
61
+ def ai_evaluate(fin: Dict[str, Any], ext_df_like: Dict[str, float] | None = None) -> Dict[str, Any]:
62
  """
63
+ AI評点(外部評価と基準を分離): 将来リスク・効率性・成長余地・資金繰り耐性・資本政策。
64
+ LLMは短評のみ使用(数値はルールベース)。ext_df_likeの値(市場成長率・商品情報等)があれば加味。
 
65
  """
66
+ bs = fin.get("balance_sheet", {}) or {}
67
+ is_ = fin.get("income_statement", {}) or {}
68
+ cf = fin.get("cash_flows", {}) or {}
69
+
70
+ def _to_f(x):
71
+ if x in (None, "", "null"): return None
72
+ try: return float(str(x).replace(",","").replace("▲","-").replace("△","-"))
73
+ except Exception: return None
74
+
75
+ sales = _to_f(is_.get("sales"))
76
+ op = _to_f(is_.get("operating_income"))
77
+ ni = _to_f(is_.get("net_income"))
78
+ assets = _to_f(bs.get("total_assets"))
79
+ liab = _to_f(bs.get("total_liabilities"))
80
+ equity = _to_f(bs.get("total_equity"))
81
+ ca = _to_f(bs.get("current_assets"))
82
+ cl = _to_f(bs.get("current_liabilities"))
83
+ ocf = _to_f(cf.get("operating_cash_flow"))
84
+
85
+ def ratio(a,b):
86
+ if a is None or b is None or b==0: return None
87
+ return a/b
88
+ def ramp(x, good, bad, lo=0, hi=10):
89
+ if x is None: return 5.0
90
+ if good>bad:
91
+ if x<=bad: return lo
92
+ if x>=good: return hi
93
+ return lo+(hi-lo)*(x-bad)/(good-bad)
94
+ else:
95
+ if x>=bad: return lo
96
+ if x<=good: return hi
97
+ return lo+(hi-lo)*(x-good)/(bad-good)
98
+ def clamp01(x): return max(0.0, min(10.0, x))
99
+
100
+ # ①効率性: 回転・収益性
101
+ margin = ratio(op, sales) # 営業利益率
102
+ at = ratio(sales, assets) # 総資産回転率
103
+ eff = (ramp(margin, 0.12, 0.01) + ramp(at, 1.3, 0.3)) / 2
104
+
105
+ # ②資金繰り耐性: 流動比率+営業CF/売上
106
+ cr = ratio(ca, cl) # 流動比率
107
+ ocf_ms = ratio(ocf, sales)
108
+ cashbuf = (ramp(cr, 1.5, 0.7) + ramp(ocf_ms, 0.1, -0.05)) / 2
109
+
110
+ # ③資本政策・希薄化リスク: 負債比率+純利益/自己資本
111
+ lev = ratio(liab, assets)
112
+ roe_proxy = ratio(ni, equity)
113
+ cap = (ramp(lev, 0.3, 0.9) + ramp(roe_proxy, 0.10, -0.05)) / 2
114
+
115
+ # ④成長余地: 市場成長+現在の収益性レベル
116
+ market_g = None
117
+ prod_factor = 5.0
118
+ if ext_df_like:
119
+ market_g = ext_df_like.get("市場の年成長率(%)")
120
+ grow_items = ext_df_like.get("成長中主力商品数")
121
+ prod_total = ext_df_like.get("主力商品数")
122
+ if prod_total:
123
+ r = (grow_items or 0)/prod_total
124
+ prod_factor = clamp01(10.0*r) # 成長中比率を0-10に
125
+
126
+ growth = (ramp(None if market_g is None else market_g/100.0, 0.15, -0.05) + prod_factor)/2
127
+
128
+ # ⑤将来リスク: 利益率の低さやレバレッジ上昇をマイナス評価
129
+ risk = 10.0 - ((ramp(margin, 0.12, 0.01) + ramp(lev, 0.3, 0.9))/2)
130
+
131
+ # 重み(外部評価と差別化)
132
+ weights = {
133
+ "効率性": 0.25,
134
+ "資金繰り耐性": 0.20,
135
+ "資本政策・希薄化": 0.20,
136
+ "成長余地": 0.20,
137
+ "将来リスク": 0.15,
138
+ }
139
+ cats = {
140
+ "効率性": eff, "資金繰り耐性": cashbuf, "資本政策・希薄化": cap,
141
+ "成長余地": growth, "将来リスク": risk
142
+ }
143
+ total_0_10 = sum(cats[k]*w for k,w in weights.items())
144
+ total = round(total_0_10*10.0, 1) # 0-100換算
145
+
146
+ grade = "S" if total>=85 else "A" if total>=75 else "B" if total>=65 else "C" if total>=50 else "D"
147
+
148
+ # 短評(LLM)
149
+ memo = ""
150
  try:
151
+ cli = _client()
152
+ memo_prompt = f"""以下の財務数値(推定含む)を踏まえ、「良い点3つ」「懸念3つ」「総評(100字以内)」を簡潔に日本語で:
153
+ [主要比率] 営業利益率={margin or '—'} / 総資産回転率={at or '—'} / 流動比率={cr or '—'}
154
+ [市場成長率(%)]={market_g or '—'} / 成長中商品比 ~ {prod_factor*10:.0f}% (概算)
155
+ """
156
+ resp = cli.chat.completions.create(
157
+ model=OPENAI_MODEL_TEXT,
158
+ messages=[
159
+ {"role": "system", "content": "簡潔・中立な財務アナリスト。数値に即した短評を出力。"},
160
+ {"role": "user", "content": memo_prompt},
161
+ ],
162
+ temperature=0.3,
163
+ )
164
+ memo = resp.choices[0].message.content.strip()
165
+ except Exception:
166
+ memo = "短評生成に失敗しました(ネットワーク/鍵設定をご確認ください)。"
167
+
168
+ return {
169
+ "ai_total": total,
170
+ "grade": grade,
171
+ "category_scores": {k: round(v*10.0,1) for k,v in cats.items()},
172
+ "weights": weights,
173
+ "memo": memo,
174
+ }