Update app.py
Browse files
app.py
CHANGED
@@ -1,1097 +1,35 @@
|
|
1 |
-
"""
|
2 |
-
K-Listed Company Analysis Agent - Enhanced Async with Multi-Agent Collaboration
|
3 |
-
Using Qwen3-235B model with Investigator/Auditor/Supervisor team
|
4 |
-
"""
|
5 |
-
|
6 |
import os
|
7 |
import sys
|
8 |
-
import json
|
9 |
-
import time
|
10 |
-
import traceback
|
11 |
-
import sqlite3
|
12 |
-
import pickle
|
13 |
-
import asyncio
|
14 |
-
import aiohttp
|
15 |
-
from typing import List, Dict, Optional, Tuple, Any
|
16 |
-
from datetime import datetime, timedelta
|
17 |
-
from dataclasses import dataclass, field, asdict
|
18 |
-
from concurrent.futures import ThreadPoolExecutor, as_completed
|
19 |
-
import re
|
20 |
-
import hashlib
|
21 |
-
|
22 |
import streamlit as st
|
23 |
-
|
24 |
-
import plotly.graph_objects as go
|
25 |
-
import plotly.express as px
|
26 |
-
import requests
|
27 |
-
import yfinance as yf
|
28 |
-
|
29 |
-
# Set page config at the very beginning
|
30 |
-
st.set_page_config(
|
31 |
-
page_title="π°π· K-Listed Company Analysis Agent",
|
32 |
-
page_icon="π°π·",
|
33 |
-
layout="wide",
|
34 |
-
initial_sidebar_state="expanded"
|
35 |
-
)
|
36 |
-
|
37 |
-
# =============================================================================
|
38 |
-
# Configuration
|
39 |
-
# =============================================================================
|
40 |
-
APP_TITLE = "π°π· K-Listed Company Analysis Agent (KOSPI/KOSDAQ)"
|
41 |
-
APP_DESC = """
|
42 |
-
νκ΅ μμ₯μ¬ μ λ¬Έ AI λΆμ μμ€ν
- Multi-Agent Collaboration
|
43 |
-
- π€ 3λ¨κ³ νμ
: μ‘°μ¬μ β κ°μ¬μ β κ°λ
μ
|
44 |
-
- π Qwen3-235B λͺ¨λΈ (12,000 ν ν°)
|
45 |
-
- β‘ λΉλκΈ° λ³λ ¬ μ²λ¦¬
|
46 |
-
- π 2,600+ μ μμ₯μ¬ μ§μ
|
47 |
-
"""
|
48 |
-
|
49 |
-
# Fireworks Configuration - QWEN MODEL
|
50 |
-
FIREWORKS_MODEL = "accounts/fireworks/models/qwen3-235b-a22b-instruct-2507"
|
51 |
-
FIREWORKS_URL = "https://api.fireworks.ai/inference/v1/chat/completions"
|
52 |
-
BRAVE_URL = "https://api.search.brave.com/res/v1/web/search"
|
53 |
-
|
54 |
-
# Token allocation for multi-agent system
|
55 |
-
TOKEN_ALLOCATION = {
|
56 |
-
"investigator": 4096,
|
57 |
-
"auditor": 2048,
|
58 |
-
"supervisor": 4096,
|
59 |
-
"total": 12000
|
60 |
-
}
|
61 |
-
|
62 |
-
ALLOWED_OFFICIAL_DOMAINS = [
|
63 |
-
"dart.fss.or.kr",
|
64 |
-
"kind.krx.co.kr",
|
65 |
-
"krx.co.kr",
|
66 |
-
"www.krx.co.kr",
|
67 |
-
"finance.naver.com",
|
68 |
-
"comp.fnguide.com",
|
69 |
-
]
|
70 |
-
|
71 |
-
# Database
|
72 |
-
DB_PATH = "korean_stocks.db"
|
73 |
-
CACHE_EXPIRY_HOURS = 24
|
74 |
-
|
75 |
-
# Sample Korean stocks data
|
76 |
-
KOREAN_STOCKS_DATA = [
|
77 |
-
# KOSPI
|
78 |
-
("005930", "μΌμ±μ μ", "KOSPI", "μ κΈ°μ μ", "λ°λ체"),
|
79 |
-
("000660", "SKνμ΄λμ€", "KOSPI", "μ κΈ°μ μ", "λ°λ체"),
|
80 |
-
("373220", "LGμλμ§μ루μ
", "KOSPI", "μ κΈ°μ μ", "λ°°ν°λ¦¬"),
|
81 |
-
("207940", "μΌμ±λ°μ΄μ€λ‘μ§μ€", "KOSPI", "μμ½ν", "λ°μ΄μ€"),
|
82 |
-
("005380", "νλμ°¨", "KOSPI", "μ΄μμ₯λΉ", "μλμ°¨"),
|
83 |
-
("000270", "κΈ°μ", "KOSPI", "μ΄μμ₯λΉ", "μλμ°¨"),
|
84 |
-
("068270", "μ
νΈλ¦¬μ¨", "KOSPI", "μμ½ν", "λ°μ΄μ€"),
|
85 |
-
("035720", "μΉ΄μΉ΄μ€", "KOSPI", "μλΉμ€μ
", "μΈν°λ·"),
|
86 |
-
("035420", "λ€μ΄λ²", "KOSPI", "μλΉμ€μ
", "μΈν°λ·"),
|
87 |
-
("006400", "μΌμ±SDI", "KOSPI", "μ κΈ°μ μ", "λ°°ν°λ¦¬"),
|
88 |
-
("051910", "LGνν", "KOSPI", "νν", "μμ νν"),
|
89 |
-
("005490", "ν¬μ€μ½νλ©μ€", "KOSPI", "μ² κ°κΈμ", "μ² κ°"),
|
90 |
-
("012330", "νλλͺ¨λΉμ€", "KOSPI", "μ΄μμ₯λΉ", "μλμ°¨λΆν"),
|
91 |
-
("105560", "KBκΈμ΅", "KOSPI", "κΈμ΅μ
", "μν"),
|
92 |
-
("055550", "μ νμ§μ£Ό", "KOSPI", "κΈμ΅μ
", "μν"),
|
93 |
-
# KOSDAQ
|
94 |
-
("247540", "μμ½νλ‘λΉμ ", "KOSDAQ", "μ κΈ°μ μ", "λ°°ν°λ¦¬μμ¬"),
|
95 |
-
("086520", "μμ½νλ‘", "KOSDAQ", "μ κΈ°μ μ", "νκ²½"),
|
96 |
-
("328130", "루λ", "KOSDAQ", "μλ£", "AIμλ£"),
|
97 |
-
("196170", "μν
μ€μ ", "KOSDAQ", "μμ½ν", "λ°μ΄μ€"),
|
98 |
-
("326030", "SKλ°μ΄μ€ν", "KOSDAQ", "μμ½ν", "μ μ½"),
|
99 |
-
]
|
100 |
-
|
101 |
-
# =============================================================================
|
102 |
-
# Data Classes
|
103 |
-
# =============================================================================
|
104 |
-
@dataclass
|
105 |
-
class SearchResult:
|
106 |
-
url: str
|
107 |
-
title: str
|
108 |
-
description: str
|
109 |
-
hostname: str
|
110 |
-
|
111 |
-
@dataclass
|
112 |
-
class AnalysisReport:
|
113 |
-
company: str
|
114 |
-
ticker: str = ""
|
115 |
-
market: str = ""
|
116 |
-
report_text: str = ""
|
117 |
-
sources: List[SearchResult] = field(default_factory=list)
|
118 |
-
timestamp: str = ""
|
119 |
-
error: str = ""
|
120 |
-
stock_data: Optional[pd.DataFrame] = None
|
121 |
-
financial_info: Optional[Dict] = None
|
122 |
-
from_cache: bool = False
|
123 |
-
processing_time: float = 0.0
|
124 |
-
agent_outputs: Dict[str, str] = field(default_factory=dict)
|
125 |
-
|
126 |
-
# =============================================================================
|
127 |
-
# Utility Functions
|
128 |
-
# =============================================================================
|
129 |
-
def _now_kst() -> str:
|
130 |
-
"""Get current KST timestamp"""
|
131 |
-
kst = datetime.utcnow() + timedelta(hours=9)
|
132 |
-
return kst.strftime("%Y-%m-%d %H:%M:%S KST")
|
133 |
-
|
134 |
-
def ensure_env() -> List[str]:
|
135 |
-
"""Check required environment variables"""
|
136 |
-
missing = []
|
137 |
-
if not os.getenv("BRAVE_API_KEY"):
|
138 |
-
missing.append("BRAVE_API_KEY")
|
139 |
-
if not os.getenv("FIREWORKS_API_KEY"):
|
140 |
-
missing.append("FIREWORKS_API_KEY")
|
141 |
-
return missing
|
142 |
-
|
143 |
-
def safe_get(dct: Dict, path: str, default=None):
|
144 |
-
"""Safely get nested dictionary values"""
|
145 |
-
cur = dct
|
146 |
-
for p in path.split("."):
|
147 |
-
if not isinstance(cur, dict) or p not in cur:
|
148 |
-
return default
|
149 |
-
cur = cur[p]
|
150 |
-
return cur
|
151 |
-
|
152 |
-
# =============================================================================
|
153 |
-
# Database Functions
|
154 |
-
# =============================================================================
|
155 |
-
@st.cache_resource
|
156 |
-
def init_database():
|
157 |
-
"""Initialize SQLite database with Korean stocks"""
|
158 |
-
conn = sqlite3.connect(DB_PATH, check_same_thread=False)
|
159 |
-
cursor = conn.cursor()
|
160 |
-
|
161 |
-
cursor.execute('''
|
162 |
-
CREATE TABLE IF NOT EXISTS stocks (
|
163 |
-
ticker TEXT PRIMARY KEY,
|
164 |
-
name TEXT NOT NULL,
|
165 |
-
market TEXT NOT NULL,
|
166 |
-
sector TEXT,
|
167 |
-
industry TEXT,
|
168 |
-
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
169 |
-
)
|
170 |
-
''')
|
171 |
-
|
172 |
-
cursor.execute('''
|
173 |
-
CREATE TABLE IF NOT EXISTS analysis_cache (
|
174 |
-
cache_key TEXT PRIMARY KEY,
|
175 |
-
company TEXT NOT NULL,
|
176 |
-
report_data BLOB,
|
177 |
-
sources_data BLOB,
|
178 |
-
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
179 |
-
expires_at TIMESTAMP
|
180 |
-
)
|
181 |
-
''')
|
182 |
-
|
183 |
-
# Load stocks data
|
184 |
-
cursor.executemany(
|
185 |
-
"INSERT OR REPLACE INTO stocks (ticker, name, market, sector, industry) VALUES (?, ?, ?, ?, ?)",
|
186 |
-
KOREAN_STOCKS_DATA
|
187 |
-
)
|
188 |
-
|
189 |
-
conn.commit()
|
190 |
-
return conn
|
191 |
-
|
192 |
-
@st.cache_data(ttl=3600)
|
193 |
-
def search_stock_by_name(name: str) -> Optional[Tuple[str, str, str]]:
|
194 |
-
"""Search stock by company name"""
|
195 |
-
conn = init_database()
|
196 |
-
cursor = conn.cursor()
|
197 |
-
|
198 |
-
cursor.execute(
|
199 |
-
"SELECT ticker, name, market FROM stocks WHERE name LIKE ? OR ticker = ?",
|
200 |
-
(f"%{name}%", name)
|
201 |
-
)
|
202 |
-
result = cursor.fetchone()
|
203 |
-
return result
|
204 |
-
|
205 |
-
def save_to_cache(company: str, report: Dict, sources: List, ttl_hours: int = 24):
|
206 |
-
"""Save analysis to cache"""
|
207 |
-
conn = init_database()
|
208 |
-
cursor = conn.cursor()
|
209 |
-
|
210 |
-
cache_key = hashlib.md5(f"{company}_{datetime.now().date()}".encode()).hexdigest()
|
211 |
-
expires_at = datetime.now() + timedelta(hours=ttl_hours)
|
212 |
-
|
213 |
-
cursor.execute('''
|
214 |
-
INSERT OR REPLACE INTO analysis_cache
|
215 |
-
(cache_key, company, report_data, sources_data, expires_at)
|
216 |
-
VALUES (?, ?, ?, ?, ?)
|
217 |
-
''', (cache_key, company, pickle.dumps(report), pickle.dumps(sources), expires_at))
|
218 |
-
|
219 |
-
conn.commit()
|
220 |
-
|
221 |
-
def get_from_cache(company: str) -> Optional[Tuple[Dict, List]]:
|
222 |
-
"""Get cached analysis if available"""
|
223 |
-
conn = init_database()
|
224 |
-
cursor = conn.cursor()
|
225 |
-
|
226 |
-
cursor.execute('''
|
227 |
-
SELECT report_data, sources_data
|
228 |
-
FROM analysis_cache
|
229 |
-
WHERE company = ? AND expires_at > ?
|
230 |
-
ORDER BY created_at DESC LIMIT 1
|
231 |
-
''', (company, datetime.now()))
|
232 |
-
|
233 |
-
result = cursor.fetchone()
|
234 |
-
if result:
|
235 |
-
return pickle.loads(result[0]), pickle.loads(result[1])
|
236 |
-
return None
|
237 |
-
|
238 |
-
# =============================================================================
|
239 |
-
# Async Fireworks Client with Qwen Model
|
240 |
-
# =============================================================================
|
241 |
-
class AsyncFireworksClient:
|
242 |
-
"""Async client for Fireworks API with Qwen3-235B model"""
|
243 |
-
|
244 |
-
def __init__(self):
|
245 |
-
self.api_key = os.getenv("FIREWORKS_API_KEY")
|
246 |
-
self.model = FIREWORKS_MODEL
|
247 |
-
self.url = FIREWORKS_URL
|
248 |
-
self.session = None
|
249 |
-
|
250 |
-
async def __aenter__(self):
|
251 |
-
self.session = aiohttp.ClientSession()
|
252 |
-
return self
|
253 |
-
|
254 |
-
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
255 |
-
if self.session:
|
256 |
-
await self.session.close()
|
257 |
-
|
258 |
-
async def chat_async(self, messages: List[Dict], max_tokens: int = 4096,
|
259 |
-
temperature: float = 0.6, timeout: int = 60) -> Optional[str]:
|
260 |
-
"""Async chat with Qwen model"""
|
261 |
-
if not self.api_key:
|
262 |
-
st.error("Fireworks API key not set")
|
263 |
-
return None
|
264 |
-
|
265 |
-
if not self.session:
|
266 |
-
self.session = aiohttp.ClientSession()
|
267 |
-
|
268 |
-
headers = {
|
269 |
-
"Accept": "application/json",
|
270 |
-
"Content-Type": "application/json",
|
271 |
-
"Authorization": f"Bearer {self.api_key}"
|
272 |
-
}
|
273 |
-
|
274 |
-
payload = {
|
275 |
-
"model": self.model,
|
276 |
-
"messages": messages,
|
277 |
-
"max_tokens": max_tokens,
|
278 |
-
"top_p": 1,
|
279 |
-
"top_k": 40,
|
280 |
-
"presence_penalty": 0,
|
281 |
-
"frequency_penalty": 0,
|
282 |
-
"temperature": temperature
|
283 |
-
}
|
284 |
-
|
285 |
-
try:
|
286 |
-
async with self.session.post(
|
287 |
-
self.url,
|
288 |
-
headers=headers,
|
289 |
-
json=payload,
|
290 |
-
timeout=aiohttp.ClientTimeout(total=timeout)
|
291 |
-
) as response:
|
292 |
-
if response.status == 200:
|
293 |
-
data = await response.json()
|
294 |
-
content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
|
295 |
-
return content
|
296 |
-
else:
|
297 |
-
error_text = await response.text()
|
298 |
-
st.error(f"Fireworks API error ({response.status}): {error_text[:200]}")
|
299 |
-
return None
|
300 |
-
|
301 |
-
except asyncio.TimeoutError:
|
302 |
-
st.error(f"Timeout after {timeout} seconds")
|
303 |
-
return None
|
304 |
-
except Exception as e:
|
305 |
-
st.error(f"API call error: {str(e)}")
|
306 |
-
return None
|
307 |
-
|
308 |
-
async def multi_agent_process(self, company: str, sources: List[SearchResult],
|
309 |
-
sections: List[str], tone: str) -> Dict[str, str]:
|
310 |
-
"""Process through Investigator -> Auditor -> Supervisor agents"""
|
311 |
-
results = {}
|
312 |
-
|
313 |
-
# 1. INVESTIGATOR AGENT
|
314 |
-
st.info("π΅οΈ μ‘°μ¬μ μμ΄μ νΈ μλ μ€...")
|
315 |
-
investigator_result = await self.run_investigator(company, sources)
|
316 |
-
results['investigator'] = investigator_result
|
317 |
-
|
318 |
-
if not investigator_result:
|
319 |
-
st.error("μ‘°μ¬μ μμ΄μ νΈ μ€ν¨")
|
320 |
-
return results
|
321 |
-
|
322 |
-
# 2. AUDITOR AGENT
|
323 |
-
st.info("β
κ°μ¬μ μμ΄μ νΈ κ²μ¦ μ€...")
|
324 |
-
auditor_result = await self.run_auditor(company, investigator_result)
|
325 |
-
results['auditor'] = auditor_result
|
326 |
-
|
327 |
-
# 3. SUPERVISOR AGENT
|
328 |
-
st.info("π κ°λ
μ μμ΄μ νΈ μ΅μ’
λ³΄κ³ μ μμ± μ€...")
|
329 |
-
supervisor_result = await self.run_supervisor(
|
330 |
-
company, investigator_result, auditor_result, sections, tone
|
331 |
-
)
|
332 |
-
results['supervisor'] = supervisor_result
|
333 |
-
|
334 |
-
return results
|
335 |
-
|
336 |
-
async def run_investigator(self, company: str, sources: List[SearchResult]) -> str:
|
337 |
-
"""μ‘°μ¬μ μμ΄μ νΈ: μ 보 μμ§ λ° μ΄κΈ° λΆμ"""
|
338 |
-
source_text = "\n\n".join([
|
339 |
-
f"{i+1}. {s.title}\n{s.description}\nμΆμ²: {s.hostname}\nURL: {s.url}"
|
340 |
-
for i, s in enumerate(sources[:20])
|
341 |
-
])
|
342 |
-
|
343 |
-
system_prompt = """λΉμ μ νκ΅ μμ₯μ¬ μ λ¬Έ μ‘°μ¬ μ λ리μ€νΈμ
λλ€.
|
344 |
-
λͺ©ν: KOSPI/KOSDAQ μμ₯μ¬μ μ¬μ€ κΈ°λ° μ 보λ₯Ό 체κ³μ μΌλ‘ μμ§νκ³ μ 리ν©λλ€.
|
345 |
-
μμΉ:
|
346 |
-
1) 곡μ μΆμ²(DART, KRX) μ΅μ°μ
|
347 |
-
2) ꡬ체μ μμΉμ λ μ§ λͺ
μ
|
348 |
-
3) μΆμ κ³Ό νμ ꡬλΆ
|
349 |
-
4) κ° λ¬Έμ₯ μΆμ² νκΈ° [n]"""
|
350 |
-
|
351 |
-
user_prompt = f"""
|
352 |
-
λΆμ λμ: {company}
|
353 |
-
|
354 |
-
κ²μ κ²°κ³Ό:
|
355 |
-
{source_text}
|
356 |
-
|
357 |
-
μμΈ μ‘°μ¬ μꡬμ¬ν:
|
358 |
-
1. νμ¬ κ°μ (μ¬μ
μμ, μμ₯ μ§μ, ν΅μ¬ κ²½μλ ₯)
|
359 |
-
2. μ΅κ·Ό μ¬λ¬΄ νμ΄λΌμ΄νΈ (λ§€μΆ, μμ
μ΄μ΅, μμ΄μ΅ λ± κ΅¬μ²΄μ μμΉ)
|
360 |
-
3. μ΅κ·Ό 60μΌ μ£Όμ μ΄λ²€νΈ (곡μ, λ΄μ€, κ²½μμ§ λ°ν)
|
361 |
-
4. ν΅μ¬ 리μ€ν¬ μμΈ (3-5κ°)
|
362 |
-
5. μ±μ₯ μΉ΄ν리μ€νΈ (3-5κ°)
|
363 |
-
6. κ²½μ νκ²½ λ° μμ₯ ν¬μ§μ
|
364 |
-
7. λ°Έλ₯μμ΄μ
νν© (PER, PBR λ±)
|
365 |
-
|
366 |
-
κ° μΉμ
λ³λ‘ ꡬ체μ μμΉμ λ μ§λ₯Ό ν¬ν¨νκ³ , λͺ¨λ μ£Όμ₯μ [n] μΆμ² νκΈ°.
|
367 |
-
"""
|
368 |
-
|
369 |
-
messages = [
|
370 |
-
{"role": "system", "content": system_prompt},
|
371 |
-
{"role": "user", "content": user_prompt}
|
372 |
-
]
|
373 |
-
|
374 |
-
return await self.chat_async(messages, max_tokens=TOKEN_ALLOCATION['investigator'], temperature=0.4)
|
375 |
-
|
376 |
-
async def run_auditor(self, company: str, investigation: str) -> str:
|
377 |
-
"""κ°μ¬μ μμ΄μ νΈ: μ¬μ€ κ²μ¦ λ° νμ§ κ΄λ¦¬"""
|
378 |
-
system_prompt = """λΉμ μ ν¬μ 리μμΉ νμ§κ΄λ¦¬ μ±
μμμ
λλ€.
|
379 |
-
μν : μ‘°μ¬ λ΄μ©μ μ νμ±, μμ μ±, κ°κ΄μ±μ κ²μ¦ν©λλ€.
|
380 |
-
κ²μ¦ κΈ°μ€:
|
381 |
-
1) νκ΅ μμ₯μ¬ μ¬λΆ νμΈ
|
382 |
-
2) DART/KRX μΆμ² ν¬ν¨ μ¬λΆ
|
383 |
-
3) μ«μμ λ μ§μ μ νμ±
|
384 |
-
4) κ³Όλν μΆμ μ΄λ μ£Όκ΄μ νν
|
385 |
-
5) λ
Όλ¦¬μ μΌκ΄μ±
|
386 |
-
6) μ€μ μ 보 λλ½"""
|
387 |
-
|
388 |
-
user_prompt = f"""
|
389 |
-
νμ¬: {company}
|
390 |
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
β‘ νκ΅ μμ₯μ¬(KOSPI/KOSDAQ) νμΈλ¨
|
396 |
-
β‘ DART/KRX 곡μ μΆμ² μ΅μ 2κ° μ΄μ
|
397 |
-
β‘ μ΅κ·Ό 60μΌ μ΄λ΄ μ 보 ν¬ν¨
|
398 |
-
β‘ μ¬λ¬΄ μμΉ μΌκ΄μ± λ° λ¨μ μ νμ±
|
399 |
-
β‘ μΆμ /νμ κ΅¬λΆ λͺ
ν
|
400 |
-
①리μ€ν¬μ κΈ°ν κ· νμ μμ
|
401 |
-
β‘ κ²½μμ¬ μΈκΈ λ° λΉκ΅
|
402 |
-
β‘ μΈμ© μΈλ±μ€ μμ μ±
|
403 |
-
|
404 |
-
[κ²μ¦ κ²°κ³Ό]
|
405 |
-
- μ°μν μ :
|
406 |
-
- λ¬Έμ μ :
|
407 |
-
- νμ 보μ μ¬ν:
|
408 |
-
- μΆκ° κΆμ₯ μ¬ν:
|
409 |
-
"""
|
410 |
-
|
411 |
-
messages = [
|
412 |
-
{"role": "system", "content": system_prompt},
|
413 |
-
{"role": "user", "content": user_prompt}
|
414 |
-
]
|
415 |
-
|
416 |
-
return await self.chat_async(messages, max_tokens=TOKEN_ALLOCATION['auditor'], temperature=0.2)
|
417 |
-
|
418 |
-
async def run_supervisor(self, company: str, investigation: str, audit: str,
|
419 |
-
sections: List[str], tone: str) -> str:
|
420 |
-
"""κ°λ
μ μμ΄μ νΈ: μ΅μ’
λ³΄κ³ μ μμ±"""
|
421 |
-
system_prompt = """λΉμ μ νκ΅ μ΅κ³ μ ν¬μμ λ΅ μ±
μμμ
λλ€.
|
422 |
-
μ무: μ‘°μ¬ λ΄μ©κ³Ό κ°μ¬ νΌλλ°±μ μ’
ν©νμ¬ μ λ¬Έμ μΈ ν¬μ λΆμ λ³΄κ³ μλ₯Ό μμ±ν©λλ€.
|
423 |
-
μμΉ:
|
424 |
-
1) ν¬μ μμ¬κ²°μ μ νμν ν΅μ¬ μ 보 μ°μ
|
425 |
-
2) λ°μ΄ν° κΈ°λ° κ°κ΄μ λΆμ
|
426 |
-
3) λͺ
οΏ½οΏ½ν ν¬μ ν¬μΈνΈ μ μ
|
427 |
-
4) 리μ€ν¬-λ¦¬ν΄ λ°Έλ°μ€ κ³ λ €
|
428 |
-
5) DART/KRX μΆμ² μ°μ μΈμ©"""
|
429 |
-
|
430 |
-
section_map = {
|
431 |
-
"ν¬μ ν¬μΈνΈ": "## π ν΅μ¬ ν¬μ ν¬μΈνΈ",
|
432 |
-
"νμ¬ κ°μ": "## π’ νμ¬ κ°μ λ° μ¬μ
ꡬ쑰",
|
433 |
-
"μ¬λ¬΄ λΆμ": "## π° μ¬λ¬΄ μ±κ³Ό λ° κ±΄μ μ±",
|
434 |
-
"μ΅κ·Ό μ΄μ": "## π° μ΅κ·Ό μ£Όμ μ΄λ²€νΈ λ° κ³΅μ",
|
435 |
-
"μ°μ
λΆμ": "## π μ°μ
νκ²½ λ° κ²½μ μ§μ",
|
436 |
-
"리μ€ν¬ μμΈ": "## β οΈ ν¬μ 리μ€ν¬ λΆμ",
|
437 |
-
"μ±μ₯ μ λ§": "## π μ±μ₯ λλ ₯ λ° μΉ΄ν리μ€νΈ",
|
438 |
-
"λ°Έλ₯μμ΄μ
": "## π λ°Έλ₯μμ΄μ
λ° λͺ©νμ£Όκ°",
|
439 |
-
}
|
440 |
-
|
441 |
-
requested_sections = "\n".join([section_map.get(s, f"## {s}") for s in sections])
|
442 |
-
|
443 |
-
user_prompt = f"""
|
444 |
-
νμ¬: {company}
|
445 |
-
μμ± μ€νμΌ: {tone}
|
446 |
-
|
447 |
-
[μ‘°μ¬μ λ³΄κ³ μ]
|
448 |
-
{investigation}
|
449 |
-
|
450 |
-
[κ°μ¬μ νΌλλ°±]
|
451 |
-
{audit}
|
452 |
-
|
453 |
-
[μ΅μ’
λ³΄κ³ μ μμ± μ§μΉ¨]
|
454 |
-
ν¬ν¨ μΉμ
:
|
455 |
-
{requested_sections}
|
456 |
-
|
457 |
-
νμ κ·μΉ:
|
458 |
-
1. κ° μΉμ
μ λ§ν¬λ€μ΄ ν€λ(##)λ‘ κ΅¬λΆ
|
459 |
-
2. ν΅μ¬ μμΉλ **κ΅΅κ²** νμ
|
460 |
-
3. μ€μ ν¬μΈνΈλ > μΈμ©κ΅¬λ‘ κ°μ‘°
|
461 |
-
4. νλ₯Ό νμ©ν λ°μ΄ν° μ 리
|
462 |
-
5. κ° μ£Όμ₯μ [n] μΈμ© μ μ§
|
463 |
-
6. μΉμ
λ³ ν΅μ¬ μμ½ λ°μ€
|
464 |
-
7. ν¬μμ μ‘μ
μμ΄ν
μ μ
|
465 |
-
8. λ§μ§λ§μ μΆμ² λͺ©λ‘κ³Ό λ©΄μ±
μ‘°ν
|
466 |
-
|
467 |
-
ν¬μ μμ¬κ²°μ μ μ¦μ νμ© κ°λ₯ν μμ€μΌλ‘ μμ±νμΈμ.
|
468 |
-
"""
|
469 |
-
|
470 |
-
messages = [
|
471 |
-
{"role": "system", "content": system_prompt},
|
472 |
-
{"role": "user", "content": user_prompt}
|
473 |
-
]
|
474 |
-
|
475 |
-
return await self.chat_async(messages, max_tokens=TOKEN_ALLOCATION['supervisor'], temperature=0.5)
|
476 |
-
|
477 |
-
# =============================================================================
|
478 |
-
# Sync wrapper for async operations
|
479 |
-
# =============================================================================
|
480 |
-
class FireworksMultiAgentClient:
|
481 |
-
"""Synchronous wrapper for async multi-agent system"""
|
482 |
-
|
483 |
-
def __init__(self):
|
484 |
-
self.async_client = AsyncFireworksClient()
|
485 |
-
|
486 |
-
def process_analysis(self, company: str, sources: List[SearchResult],
|
487 |
-
sections: List[str], tone: str) -> Dict[str, str]:
|
488 |
-
"""Run multi-agent analysis synchronously"""
|
489 |
-
loop = None
|
490 |
-
try:
|
491 |
-
loop = asyncio.get_event_loop()
|
492 |
-
except RuntimeError:
|
493 |
-
loop = asyncio.new_event_loop()
|
494 |
-
asyncio.set_event_loop(loop)
|
495 |
|
496 |
-
|
497 |
-
|
498 |
-
|
499 |
|
500 |
-
|
501 |
-
|
502 |
-
|
503 |
-
|
504 |
-
# =============================================================================
|
505 |
-
class BraveSearchClient:
|
506 |
-
"""Brave Search with parallel query execution"""
|
507 |
-
|
508 |
-
def __init__(self):
|
509 |
-
self.api_key = os.getenv("BRAVE_API_KEY")
|
510 |
-
self.executor = ThreadPoolExecutor(max_workers=6)
|
511 |
-
|
512 |
-
def _search_single(self, query: str, count: int = 10) -> List[SearchResult]:
|
513 |
-
"""Execute single search query"""
|
514 |
-
if not self.api_key:
|
515 |
-
return []
|
516 |
|
517 |
-
|
518 |
-
|
519 |
-
"X-Subscription-Token": self.api_key
|
520 |
-
}
|
521 |
-
params = {
|
522 |
-
"q": query,
|
523 |
-
"count": count,
|
524 |
-
"country": "kr",
|
525 |
-
"lang": "ko-KR",
|
526 |
-
"safesearch": "off"
|
527 |
-
}
|
528 |
|
|
|
529 |
try:
|
530 |
-
|
531 |
-
|
532 |
-
|
533 |
-
results = []
|
534 |
-
for item in data.get("web", {}).get("results", []):
|
535 |
-
results.append(SearchResult(
|
536 |
-
url=item.get("url", ""),
|
537 |
-
title=item.get("title", ""),
|
538 |
-
description=item.get("description", ""),
|
539 |
-
hostname=item.get("meta_url", {}).get("hostname", "")
|
540 |
-
))
|
541 |
-
return results
|
542 |
-
except Exception as e:
|
543 |
-
st.warning(f"Search failed for '{query}': {str(e)}")
|
544 |
-
return []
|
545 |
-
|
546 |
-
return []
|
547 |
-
|
548 |
-
def parallel_search(self, company: str, extra_keywords: str = "") -> List[SearchResult]:
|
549 |
-
"""Execute multiple searches in parallel"""
|
550 |
-
queries = [
|
551 |
-
f'{company} site:dart.fss.or.kr μ¬μ
λ³΄κ³ μ',
|
552 |
-
f'{company} site:kind.krx.co.kr 곡μ',
|
553 |
-
f'{company} μ΅κ·Ό μ€μ λ°ν λ§€μΆ μμ
μ΄μ΅',
|
554 |
-
f'{company} μ£Όκ° μ λ§ λͺ©νμ£Όκ° μ λ리μ€νΈ',
|
555 |
-
f'{company} κ²½μμ¬ λΉκ΅ μμ₯μ μ μ¨',
|
556 |
-
f'{company} λ΄μ€ μ΅μ 2024',
|
557 |
-
f'{company} μ μ¬μ
ν¬μ κ³ν',
|
558 |
-
f'{company} ESG μ§μκ°λ₯κ²½μ',
|
559 |
-
]
|
560 |
-
|
561 |
-
if extra_keywords:
|
562 |
-
for keyword in extra_keywords.split(','):
|
563 |
-
queries.append(f'{company} {keyword.strip()}')
|
564 |
-
|
565 |
-
all_results = []
|
566 |
-
seen_urls = set()
|
567 |
-
|
568 |
-
# Execute searches in parallel
|
569 |
-
futures = {
|
570 |
-
self.executor.submit(self._search_single, query, 10): query
|
571 |
-
for query in queries
|
572 |
-
}
|
573 |
-
|
574 |
-
progress_bar = st.progress(0)
|
575 |
-
completed = 0
|
576 |
-
|
577 |
-
for future in as_completed(futures):
|
578 |
-
query = futures[future]
|
579 |
-
results = future.result()
|
580 |
|
581 |
-
for result in results:
|
582 |
-
if result.url not in seen_urls:
|
583 |
-
seen_urls.add(result.url)
|
584 |
-
all_results.append(result)
|
585 |
-
|
586 |
-
completed += 1
|
587 |
-
progress_bar.progress(completed / len(queries))
|
588 |
-
st.caption(f"κ²μ μλ£: {query[:50]}...")
|
589 |
-
|
590 |
-
progress_bar.empty()
|
591 |
-
return all_results[:30]
|
592 |
-
|
593 |
-
# =============================================================================
|
594 |
-
# Stock Data Functions
|
595 |
-
# =============================================================================
|
596 |
-
@st.cache_data(ttl=300)
|
597 |
-
def get_stock_data(ticker: str) -> Tuple[Optional[pd.DataFrame], Optional[Dict]]:
|
598 |
-
"""Fetch stock data from Yahoo Finance"""
|
599 |
-
try:
|
600 |
-
stock = yf.Ticker(ticker)
|
601 |
-
hist_data = stock.history(period="1y")
|
602 |
-
info = stock.info
|
603 |
-
|
604 |
-
financial_info = {
|
605 |
-
"market_cap": info.get("marketCap", 0),
|
606 |
-
"pe_ratio": info.get("trailingPE", 0),
|
607 |
-
"pb_ratio": info.get("priceToBook", 0),
|
608 |
-
"dividend_yield": info.get("dividendYield", 0),
|
609 |
-
"52w_high": info.get("fiftyTwoWeekHigh", 0),
|
610 |
-
"52w_low": info.get("fiftyTwoWeekLow", 0),
|
611 |
-
"current_price": info.get("currentPrice", info.get("regularMarketPrice", 0)),
|
612 |
-
}
|
613 |
-
|
614 |
-
return hist_data, financial_info
|
615 |
-
except Exception as e:
|
616 |
-
st.warning(f"μ£Όκ° λ°μ΄ν° μ‘°ν μ€ν¨: {e}")
|
617 |
-
return None, None
|
618 |
-
|
619 |
-
def create_stock_chart(stock_data: pd.DataFrame, company: str, market: str) -> go.Figure:
|
620 |
-
"""Create interactive stock price chart"""
|
621 |
-
fig = go.Figure()
|
622 |
-
|
623 |
-
# Candlestick
|
624 |
-
fig.add_trace(go.Candlestick(
|
625 |
-
x=stock_data.index,
|
626 |
-
open=stock_data['Open'],
|
627 |
-
high=stock_data['High'],
|
628 |
-
low=stock_data['Low'],
|
629 |
-
close=stock_data['Close'],
|
630 |
-
name='μ£Όκ°',
|
631 |
-
increasing_line_color='red',
|
632 |
-
decreasing_line_color='blue'
|
633 |
-
))
|
634 |
-
|
635 |
-
# Moving averages
|
636 |
-
if len(stock_data) > 20:
|
637 |
-
ma20 = stock_data['Close'].rolling(window=20).mean()
|
638 |
-
fig.add_trace(go.Scatter(
|
639 |
-
x=stock_data.index,
|
640 |
-
y=ma20,
|
641 |
-
name='20μΌ μ΄λνκ· ',
|
642 |
-
line=dict(color='orange', width=1)
|
643 |
-
))
|
644 |
-
|
645 |
-
if len(stock_data) > 60:
|
646 |
-
ma60 = stock_data['Close'].rolling(window=60).mean()
|
647 |
-
fig.add_trace(go.Scatter(
|
648 |
-
x=stock_data.index,
|
649 |
-
y=ma60,
|
650 |
-
name='60μΌ μ΄λνκ· ',
|
651 |
-
line=dict(color='purple', width=1)
|
652 |
-
))
|
653 |
-
|
654 |
-
# Volume
|
655 |
-
fig.add_trace(go.Bar(
|
656 |
-
x=stock_data.index,
|
657 |
-
y=stock_data['Volume'],
|
658 |
-
name='κ±°λλ',
|
659 |
-
marker_color='rgba(100,100,100,0.3)',
|
660 |
-
yaxis='y2'
|
661 |
-
))
|
662 |
-
|
663 |
-
fig.update_layout(
|
664 |
-
title=f'{company} ({market}) μ£Όκ° μ°¨νΈ',
|
665 |
-
yaxis_title='μ£Όκ° (μ)',
|
666 |
-
yaxis2=dict(
|
667 |
-
title='κ±°λλ',
|
668 |
-
overlaying='y',
|
669 |
-
side='right'
|
670 |
-
),
|
671 |
-
xaxis_rangeslider_visible=False,
|
672 |
-
height=500,
|
673 |
-
hovermode='x unified',
|
674 |
-
template='plotly_white'
|
675 |
-
)
|
676 |
-
|
677 |
-
return fig
|
678 |
-
|
679 |
-
# =============================================================================
|
680 |
-
# Main Analysis Pipeline
|
681 |
-
# =============================================================================
|
682 |
-
def run_analysis_pipeline(company: str, tone: str, sections: List[str],
|
683 |
-
extra_keywords: str, use_cache: bool = True) -> AnalysisReport:
|
684 |
-
"""Run the complete multi-agent analysis pipeline"""
|
685 |
-
start_time = time.time()
|
686 |
-
|
687 |
-
report = AnalysisReport(
|
688 |
-
company=company,
|
689 |
-
timestamp=_now_kst()
|
690 |
-
)
|
691 |
-
|
692 |
-
# Check cache first
|
693 |
-
if use_cache:
|
694 |
-
cached = get_from_cache(company)
|
695 |
-
if cached:
|
696 |
-
report_data, sources = cached
|
697 |
-
report.report_text = report_data.get('report_text', '')
|
698 |
-
report.sources = sources
|
699 |
-
report.from_cache = True
|
700 |
-
st.success("β
μΊμλ λΆμ κ²°κ³Όλ₯Ό λΆλ¬μμ΅λλ€.")
|
701 |
-
return report
|
702 |
-
|
703 |
-
# Check environment
|
704 |
-
missing = ensure_env()
|
705 |
-
if missing:
|
706 |
-
report.error = f"νκ²½λ³μ λλ½: {', '.join(missing)}"
|
707 |
-
return report
|
708 |
-
|
709 |
-
# Get stock info from database
|
710 |
-
stock_info = search_stock_by_name(company)
|
711 |
-
if stock_info:
|
712 |
-
ticker, official_name, market = stock_info
|
713 |
-
report.ticker = ticker
|
714 |
-
report.market = market
|
715 |
-
company = official_name # Use official name
|
716 |
-
|
717 |
-
# Get stock data
|
718 |
-
ticker_yf = f"{ticker}.KS" if market == "KOSPI" else f"{ticker}.KQ"
|
719 |
-
report.stock_data, report.financial_info = get_stock_data(ticker_yf)
|
720 |
-
|
721 |
-
# Progress tracking
|
722 |
-
progress = st.progress(0)
|
723 |
-
status = st.empty()
|
724 |
-
|
725 |
-
# Step 1: Parallel search for evidence collection
|
726 |
-
status.text("π μ 보 μμ§ μ€ (λ³λ ¬ κ²μ)...")
|
727 |
-
progress.progress(20)
|
728 |
-
|
729 |
-
search_client = BraveSearchClient()
|
730 |
-
sources = search_client.parallel_search(company, extra_keywords)
|
731 |
-
report.sources = sources
|
732 |
-
|
733 |
-
if len(sources) < 5:
|
734 |
-
report.error = "μΆ©λΆν μ 보λ₯Ό μμ§νμ§ λͺ»νμ΅λλ€."
|
735 |
-
return report
|
736 |
-
|
737 |
-
# Step 2: Multi-Agent Processing
|
738 |
-
status.text("π€ λ€μ€ μμ΄μ νΈ νμ
λΆμ μ€...")
|
739 |
-
progress.progress(40)
|
740 |
-
|
741 |
-
agent_client = FireworksMultiAgentClient()
|
742 |
-
|
743 |
-
try:
|
744 |
-
# Run multi-agent analysis
|
745 |
-
agent_results = agent_client.process_analysis(
|
746 |
-
company=company,
|
747 |
-
sources=sources,
|
748 |
-
sections=sections,
|
749 |
-
tone=tone
|
750 |
-
)
|
751 |
-
|
752 |
-
report.agent_outputs = agent_results
|
753 |
-
|
754 |
-
# Get final report from supervisor
|
755 |
-
final_report = agent_results.get('supervisor', '')
|
756 |
-
|
757 |
-
if not final_report:
|
758 |
-
# Fallback to investigator report if supervisor failed
|
759 |
-
final_report = agent_results.get('investigator', '')
|
760 |
-
|
761 |
-
if not final_report:
|
762 |
-
report.error = "λ³΄κ³ μ μμ± μ€ν¨"
|
763 |
-
return report
|
764 |
-
|
765 |
-
# Format final report
|
766 |
-
header = f"""# π {company} ν¬μ λΆμ λ³΄κ³ μ
|
767 |
-
|
768 |
-
**μμ±μΌμ**: {report.timestamp}
|
769 |
-
**μμ₯**: {report.market if report.market else 'N/A'}
|
770 |
-
**μ’
λͺ©μ½λ**: {report.ticker if report.ticker else 'N/A'}
|
771 |
-
**λΆμ μμ€ν
**: Multi-Agent Collaboration (Qwen3-235B)
|
772 |
-
|
773 |
-
---
|
774 |
-
|
775 |
-
"""
|
776 |
-
|
777 |
-
# Add sources
|
778 |
-
sources_text = "\n\n## π μ°Έκ³ μλ£\n\n"
|
779 |
-
for i, source in enumerate(sources[:15], 1):
|
780 |
-
sources_text += f"[{i}] [{source.title}]({source.url})\n"
|
781 |
-
|
782 |
-
disclaimer = """
|
783 |
-
|
784 |
-
---
|
785 |
-
|
786 |
-
### β οΈ ν¬μ μ μμ¬ν
|
787 |
-
λ³Έ λ³΄κ³ μλ AI κΈ°λ° μλ λΆμμΌλ‘ μμ±λμμΌλ©°, ν¬μ νλ¨μ μ±
μμ ν¬μμ λ³ΈμΈμκ² μμ΅λλ€.
|
788 |
-
"""
|
789 |
-
|
790 |
-
report.report_text = header + final_report + sources_text + disclaimer
|
791 |
-
|
792 |
-
# Save to cache
|
793 |
-
if use_cache:
|
794 |
-
save_to_cache(
|
795 |
-
company,
|
796 |
-
{'report_text': report.report_text},
|
797 |
-
sources,
|
798 |
-
ttl_hours=CACHE_EXPIRY_HOURS
|
799 |
-
)
|
800 |
-
|
801 |
except Exception as e:
|
802 |
-
|
803 |
-
|
804 |
-
|
805 |
-
|
806 |
-
# Complete
|
807 |
-
report.processing_time = time.time() - start_time
|
808 |
-
status.text(f"β
λΆμ μλ£! (μ²λ¦¬μκ°: {report.processing_time:.1f}μ΄)")
|
809 |
-
progress.progress(100)
|
810 |
-
|
811 |
-
time.sleep(1)
|
812 |
-
progress.empty()
|
813 |
-
status.empty()
|
814 |
-
|
815 |
-
return report
|
816 |
-
|
817 |
-
# =============================================================================
|
818 |
-
# Streamlit UI
|
819 |
-
# =============================================================================
|
820 |
-
def main():
|
821 |
-
# Initialize database
|
822 |
-
init_database()
|
823 |
-
|
824 |
-
# Title and description
|
825 |
-
st.title(APP_TITLE)
|
826 |
-
st.markdown(APP_DESC)
|
827 |
-
st.divider()
|
828 |
-
|
829 |
-
# Environment check
|
830 |
-
missing_env = ensure_env()
|
831 |
-
if missing_env:
|
832 |
-
st.error(f"β οΈ νμ νκ²½λ³μκ° μ€μ λμ§ μμμ΅λλ€: {', '.join(missing_env)}")
|
833 |
-
|
834 |
-
col1, col2 = st.columns(2)
|
835 |
-
with col1:
|
836 |
-
st.info(f"""
|
837 |
-
**νμ¬ μν:**
|
838 |
-
- BRAVE_API_KEY: {'β
' if os.getenv('BRAVE_API_KEY') else 'β'}
|
839 |
-
- FIREWORKS_API_KEY: {'β
' if os.getenv('FIREWORKS_API_KEY') else 'β'}
|
840 |
-
""")
|
841 |
-
|
842 |
-
with col2:
|
843 |
-
st.info(f"""
|
844 |
-
**λͺ¨λΈ μ 보:**
|
845 |
-
{FIREWORKS_MODEL}
|
846 |
-
""")
|
847 |
-
|
848 |
-
with st.expander("π§ νκ²½λ³μ μ€μ κ°μ΄λ"):
|
849 |
-
st.markdown("""
|
850 |
-
### Hugging Face Spaces:
|
851 |
-
Settings β Repository secrets
|
852 |
-
""")
|
853 |
-
st.code("""
|
854 |
-
BRAVE_API_KEY=your_brave_api_key
|
855 |
-
FIREWORKS_API_KEY=your_fireworks_api_key
|
856 |
-
""")
|
857 |
-
|
858 |
-
if not st.checkbox("λ°λͺ¨ λͺ¨λλ‘ κ³μ"):
|
859 |
-
st.stop()
|
860 |
-
|
861 |
-
# Sidebar
|
862 |
-
with st.sidebar:
|
863 |
-
st.header("βοΈ λΆμ μ€μ ")
|
864 |
-
|
865 |
-
company = st.text_input(
|
866 |
-
"νμ¬λͺ
λλ μ’
λͺ©μ½λ *",
|
867 |
-
placeholder="μ: μΌμ±μ μ, 005930",
|
868 |
-
help="νκ΅ μμ₯μ¬λͺ
λλ μ’
λͺ©μ½λ"
|
869 |
-
)
|
870 |
-
|
871 |
-
# Show stock list
|
872 |
-
with st.expander("π μ’
λͺ© 리μ€νΈ"):
|
873 |
-
conn = init_database()
|
874 |
-
stocks_df = pd.read_sql("SELECT * FROM stocks ORDER BY market, name", conn)
|
875 |
-
st.dataframe(stocks_df, height=300)
|
876 |
-
|
877 |
-
st.divider()
|
878 |
-
|
879 |
-
tone = st.radio(
|
880 |
-
"μμ± μ€νμΌ",
|
881 |
-
["κ°κ²°", "μμΈ", "μ λ¬Έμ "],
|
882 |
-
index=2,
|
883 |
-
help="μ λ¬Έμ : κΈ°κ΄ν¬μμ μμ€"
|
884 |
-
)
|
885 |
-
|
886 |
-
sections = st.multiselect(
|
887 |
-
"ν¬ν¨ μΉμ
",
|
888 |
-
["ν¬μ ν¬μΈνΈ", "νμ¬ κ°μ", "μ¬λ¬΄ λΆμ", "μ΅κ·Ό μ΄μ",
|
889 |
-
"μ°μ
λΆμ", "리μ€ν¬ μμΈ", "μ±μ₯ μ λ§", "λ°Έλ₯μμ΄μ
"],
|
890 |
-
default=["ν¬μ ν¬μΈνΈ", "νμ¬ κ°μ", "μ¬λ¬΄ λΆμ", "리μ€ν¬ μμΈ", "μ±μ₯ μ λ§"]
|
891 |
-
)
|
892 |
-
|
893 |
-
extra_keywords = st.text_area(
|
894 |
-
"μΆκ° ν€μλ",
|
895 |
-
placeholder="μ: AI, μ κΈ°μ°¨, λ°°ν°λ¦¬",
|
896 |
-
help="μ½€λ§λ‘ ꡬλΆ"
|
897 |
-
)
|
898 |
-
|
899 |
-
st.divider()
|
900 |
-
|
901 |
-
st.subheader("π§ κ³ κΈ μ΅μ
")
|
902 |
-
use_cache = st.checkbox("πΎ μΊμ μ¬μ©", value=True, help="24μκ° μΊμ")
|
903 |
-
show_agent_outputs = st.checkbox("π€ μμ΄μ νΈ μΆλ ₯ 보기", value=False)
|
904 |
-
|
905 |
-
# Token info
|
906 |
-
st.info(f"""
|
907 |
-
**Multi-Agent Token ν λΉ**
|
908 |
-
- π΅οΈ μ‘°μ¬μ: {TOKEN_ALLOCATION['investigator']:,}
|
909 |
-
- β
κ°μ¬μ: {TOKEN_ALLOCATION['auditor']:,}
|
910 |
-
- π κ°λ
μ: {TOKEN_ALLOCATION['supervisor']:,}
|
911 |
-
- **μ΄ν©**: {TOKEN_ALLOCATION['total']:,}
|
912 |
-
""")
|
913 |
-
|
914 |
-
st.divider()
|
915 |
-
|
916 |
-
analyze_button = st.button(
|
917 |
-
"π λΆμ μμ",
|
918 |
-
type="primary",
|
919 |
-
disabled=not company
|
920 |
-
)
|
921 |
-
|
922 |
-
# Main content
|
923 |
-
if analyze_button and company:
|
924 |
-
st.header(f"π {company} λΆμ κ²°κ³Ό")
|
925 |
-
|
926 |
-
# Create tabs
|
927 |
-
tabs = st.tabs([
|
928 |
-
"π λΆμ λ³΄κ³ μ",
|
929 |
-
"π μ°¨νΈ",
|
930 |
-
"π€ μμ΄μ νΈ μΆλ ₯",
|
931 |
-
"π μΆμ²",
|
932 |
-
"πΎ λ€μ΄λ‘λ"
|
933 |
-
])
|
934 |
-
|
935 |
-
# Run analysis
|
936 |
-
report = run_analysis_pipeline(
|
937 |
-
company=company.strip(),
|
938 |
-
tone=tone,
|
939 |
-
sections=sections,
|
940 |
-
extra_keywords=extra_keywords,
|
941 |
-
use_cache=use_cache
|
942 |
-
)
|
943 |
-
|
944 |
-
if report.error:
|
945 |
-
st.error(report.error)
|
946 |
-
else:
|
947 |
-
# Tab 1: Analysis Report
|
948 |
-
with tabs[0]:
|
949 |
-
if report.from_cache:
|
950 |
-
st.info("π¦ μΊμλ κ²°κ³Ό (24μκ° μ΄λ΄)")
|
951 |
-
|
952 |
-
if report.report_text:
|
953 |
-
st.markdown(report.report_text)
|
954 |
-
|
955 |
-
if report.processing_time:
|
956 |
-
st.success(f"β±οΈ μ²λ¦¬μκ°: {report.processing_time:.1f}μ΄")
|
957 |
-
else:
|
958 |
-
st.warning("λ³΄κ³ μλ₯Ό μμ±νμ§ λͺ»νμ΅λλ€.")
|
959 |
-
|
960 |
-
# Tab 2: Charts
|
961 |
-
with tabs[1]:
|
962 |
-
if report.stock_data is not None and not report.stock_data.empty:
|
963 |
-
chart = create_stock_chart(report.stock_data, company, report.market)
|
964 |
-
st.plotly_chart(chart, use_container_width=True)
|
965 |
-
|
966 |
-
if report.financial_info:
|
967 |
-
cols = st.columns(4)
|
968 |
-
metrics = [
|
969 |
-
("νμ¬κ°", "current_price", "μ"),
|
970 |
-
("PER", "pe_ratio", "λ°°"),
|
971 |
-
("PBR", "pb_ratio", "λ°°"),
|
972 |
-
("λ°°λΉμμ΅λ₯ ", "dividend_yield", "%")
|
973 |
-
]
|
974 |
-
|
975 |
-
for col, (label, key, unit) in zip(cols, metrics):
|
976 |
-
value = report.financial_info.get(key, 0)
|
977 |
-
if value > 0:
|
978 |
-
if unit == "%":
|
979 |
-
col.metric(label, f"{value*100:.2f}{unit}")
|
980 |
-
elif unit == "μ":
|
981 |
-
col.metric(label, f"{value:,.0f}{unit}")
|
982 |
-
else:
|
983 |
-
col.metric(label, f"{value:.2f}{unit}")
|
984 |
-
else:
|
985 |
-
st.info("μ°¨νΈ λ°μ΄ν°κ° μμ΅λλ€.")
|
986 |
-
|
987 |
-
# Tab 3: Agent Outputs
|
988 |
-
with tabs[2]:
|
989 |
-
if show_agent_outputs and report.agent_outputs:
|
990 |
-
st.subheader("π€ Multi-Agent νμ
κ³Όμ ")
|
991 |
-
|
992 |
-
if 'investigator' in report.agent_outputs:
|
993 |
-
with st.expander("π΅οΈ μ‘°μ¬μ μμ΄μ νΈ μΆλ ₯"):
|
994 |
-
st.markdown(report.agent_outputs['investigator'])
|
995 |
-
|
996 |
-
if 'auditor' in report.agent_outputs:
|
997 |
-
with st.expander("β
κ°μ¬μ μμ΄μ νΈ νΌλλ°±"):
|
998 |
-
st.markdown(report.agent_outputs['auditor'])
|
999 |
-
|
1000 |
-
if 'supervisor' in report.agent_outputs:
|
1001 |
-
with st.expander("π κ°λ
μ μμ΄μ νΈ μ΅μ’
"):
|
1002 |
-
st.markdown(report.agent_outputs['supervisor'])
|
1003 |
-
else:
|
1004 |
-
st.info("μμ΄μ νΈ μΆλ ₯μ λ³΄λ €λ©΄ μ΅μ
μ νμ±ννμΈμ.")
|
1005 |
-
|
1006 |
-
# Tab 4: Sources
|
1007 |
-
with tabs[3]:
|
1008 |
-
st.subheader(f"π μ°Έκ³ μλ£ ({len(report.sources)}κ°)")
|
1009 |
-
for i, source in enumerate(report.sources, 1):
|
1010 |
-
with st.expander(f"[{i}] {source.title[:80]}..."):
|
1011 |
-
st.write(f"**URL**: {source.url}")
|
1012 |
-
st.write(f"**μ€λͺ
**: {source.description}")
|
1013 |
-
st.write(f"**μΆμ²**: {source.hostname}")
|
1014 |
-
|
1015 |
-
# Tab 5: Download
|
1016 |
-
with tabs[4]:
|
1017 |
-
st.subheader("πΎ λ³΄κ³ μ λ€μ΄λ‘λ")
|
1018 |
-
|
1019 |
-
# Prepare download content
|
1020 |
-
download_content = report.report_text
|
1021 |
-
|
1022 |
-
# JSON export
|
1023 |
-
export_data = {
|
1024 |
-
'company': company,
|
1025 |
-
'ticker': report.ticker,
|
1026 |
-
'market': report.market,
|
1027 |
-
'timestamp': report.timestamp,
|
1028 |
-
'processing_time': report.processing_time,
|
1029 |
-
'report': report.report_text,
|
1030 |
-
'sources': [
|
1031 |
-
{'title': s.title, 'url': s.url}
|
1032 |
-
for s in report.sources
|
1033 |
-
]
|
1034 |
-
}
|
1035 |
-
|
1036 |
-
col1, col2 = st.columns(2)
|
1037 |
-
|
1038 |
-
with col1:
|
1039 |
-
st.download_button(
|
1040 |
-
label="π Markdown λ€μ΄λ‘λ",
|
1041 |
-
data=download_content,
|
1042 |
-
file_name=f"{company}_analysis_{datetime.now().strftime('%Y%m%d_%H%M')}.md",
|
1043 |
-
mime="text/markdown"
|
1044 |
-
)
|
1045 |
-
|
1046 |
-
with col2:
|
1047 |
-
st.download_button(
|
1048 |
-
label="π JSON λ€μ΄λ‘λ",
|
1049 |
-
data=json.dumps(export_data, ensure_ascii=False, indent=2),
|
1050 |
-
file_name=f"{company}_data_{datetime.now().strftime('%Y%m%d_%H%M')}.json",
|
1051 |
-
mime="application/json"
|
1052 |
-
)
|
1053 |
-
|
1054 |
-
# Help section
|
1055 |
-
if not analyze_button:
|
1056 |
-
with st.container():
|
1057 |
-
st.header("π Multi-Agent System μκ°")
|
1058 |
-
|
1059 |
-
cols = st.columns(3)
|
1060 |
-
|
1061 |
-
with cols[0]:
|
1062 |
-
st.markdown("""
|
1063 |
-
### π΅οΈ μ‘°μ¬μ (Investigator)
|
1064 |
-
- μ 보 μμ§ λ° μ΄κΈ° λΆμ
|
1065 |
-
- DART/KRX 곡μ μ°μ
|
1066 |
-
- μ¬λ¬΄ λ°μ΄ν° μΆμΆ
|
1067 |
-
- μ΅κ·Ό μ΄λ²€νΈ μ 리
|
1068 |
-
""")
|
1069 |
-
|
1070 |
-
with cols[1]:
|
1071 |
-
st.markdown("""
|
1072 |
-
### β
κ°μ¬μ (Auditor)
|
1073 |
-
- μ¬μ€ κ²μ¦
|
1074 |
-
- μΆμ² νμΈ
|
1075 |
-
- λ
Όλ¦¬μ μΌκ΄μ± 체ν¬
|
1076 |
-
- λλ½ μ 보 μ§μ
|
1077 |
-
""")
|
1078 |
-
|
1079 |
-
with cols[2]:
|
1080 |
-
st.markdown("""
|
1081 |
-
### π κ°λ
μ (Supervisor)
|
1082 |
-
- μ΅μ’
λ³΄κ³ μ μμ±
|
1083 |
-
- ν¬μ κ΄μ μ 리
|
1084 |
-
- 리μ€ν¬/κΈ°ν κ· ν
|
1085 |
-
- μ‘μ
μμ΄ν
μ μ
|
1086 |
-
""")
|
1087 |
-
|
1088 |
-
# Footer
|
1089 |
-
st.divider()
|
1090 |
-
st.caption(f"""
|
1091 |
-
Last updated: {_now_kst()} |
|
1092 |
-
Powered by Qwen3-235B & Multi-Agent Collaboration |
|
1093 |
-
Supporting ALL Korean Listed Companies
|
1094 |
-
""")
|
1095 |
|
1096 |
if __name__ == "__main__":
|
1097 |
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
import sys
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
import streamlit as st
|
4 |
+
from tempfile import NamedTemporaryFile
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
|
11 |
+
if not code:
|
12 |
+
st.error("β οΈ The application code wasn't found in secrets. Please add the MAIN_CODE secret.")
|
13 |
+
return
|
14 |
|
15 |
+
# Create a temporary Python file
|
16 |
+
with NamedTemporaryFile(suffix='.py', delete=False, mode='w') as tmp:
|
17 |
+
tmp.write(code)
|
18 |
+
tmp_path = tmp.name
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
|
20 |
+
# Execute the code
|
21 |
+
exec(compile(code, tmp_path, 'exec'), globals())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
22 |
|
23 |
+
# Clean up the temporary file
|
24 |
try:
|
25 |
+
os.unlink(tmp_path)
|
26 |
+
except:
|
27 |
+
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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