benjamin5607 commited on
Commit
bdd0516
Β·
verified Β·
1 Parent(s): 82c689c

Update streamlit_app.py

Browse files
Files changed (1) hide show
  1. streamlit_app.py +129 -83
streamlit_app.py CHANGED
@@ -20,23 +20,78 @@ else:
20
  st.stop()
21
 
22
  # ==============================================================================
23
- # πŸ•΅οΈ [생쑴 기술] μ›Ή κ²€μƒ‰μœΌλ‘œ 가격 κ°•μ œ μΆ”μΆœ
24
  # ==============================================================================
25
- def scrape_price_from_web(name, ticker):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  try:
27
  with DDGS() as ddgs:
28
- query = f"{name} {ticker} stock price quote today"
29
- results = ddgs.text(query, max_results=3)
30
- text_blob = " ".join([r['body'] for r in results])
31
- match = re.search(r'(\d{1,3}(,\d{3})*(\.\d+)?)', text_blob)
32
- if match:
33
- price = float(match.group(0).replace(",", ""))
34
- return price, 0.0
35
- return None, None
36
- except: return None, None
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
  # ==============================================================================
39
- # πŸ› οΈ [핡심 μ—”μ§„] 3단계 데이터 μˆ˜μ§‘
40
  # ==============================================================================
41
  def get_price_data_robust(ticker, name):
42
  # 1. FDR
@@ -49,14 +104,9 @@ def get_price_data_robust(ticker, name):
49
  hist = fdr.DataReader(fdr_symbol, start=(datetime.datetime.now() - datetime.timedelta(days=10)))
50
  if not hist.empty:
51
  curr = hist['Close'].iloc[-1]
52
- # [μ•ˆμ „μž₯치 μΆ”κ°€] 데이터가 1쀄밖에 없을 경우 λŒ€λΉ„
53
  prev = hist['Close'].iloc[-2] if len(hist) > 1 else curr
54
-
55
- # 전일가가 0이면 등락λ₯  계산 λΆˆκ°€
56
  pct = 0.0
57
- if prev != 0:
58
- pct = ((curr - prev)/prev)*100
59
-
60
  return curr, pct, "FDR"
61
  except: pass
62
 
@@ -70,49 +120,28 @@ def get_price_data_robust(ticker, name):
70
  return price, pct, "Yahoo"
71
  except: pass
72
 
73
- # 3. Web Search
74
- price, pct = scrape_price_from_web(name, ticker)
75
- if price is not None: return price, pct if pct else 0.0, "Web Search πŸ•΅οΈ"
76
-
77
- return None, None, "Fail"
78
-
79
- # ==============================================================================
80
- # 🧠 [μ—”μ§„] AI 검색 및 λ‰΄μŠ€
81
- # ==============================================================================
82
- def identify_target_with_ai(user_query):
83
- try:
84
- prompt = f"""
85
- [ROLE] Financial Entity Resolver. [QUERY] "{user_query}"
86
- [TASK] Identify company, ticker, news keyword.
87
- [OUTPUT JSON] {{ "name": "English Name", "ticker": "TICKER", "search_keyword": "Keyword" }}
88
- """
89
- messages = [{"role": "user", "content": prompt}]
90
- response = client.chat.completions.create(model="Qwen/Qwen2.5-72B-Instruct", messages=messages, max_tokens=150)
91
- content = re.sub(r"```json|```", "", response.choices[0].message.content.strip()).strip()
92
- return json.loads(content)
93
- except: return None
94
-
95
- def get_news(keyword):
96
- summary = ""
97
  try:
98
  with DDGS() as ddgs:
99
- results = ddgs.news(keyword, timelimit="m", max_results=5)
100
- for r in results: summary += f"[{r.get('date','?')}] {r['title']}\n"
101
- return summary if summary else "No recent news."
102
- except: return "Search Error"
103
-
104
- def parse_stream(stream):
105
- for chunk in stream:
106
- if chunk.choices: yield chunk.choices[0].delta.content or ""
 
 
 
107
 
108
- # 차트용 데이터 μˆ˜μ§‘
109
  def get_chart_data(ticker):
110
  try:
111
  fdr_symbol = ticker
112
  if ".VN" in ticker: fdr_symbol = ticker.split('.')[0]
113
  elif ".JK" in ticker: fdr_symbol = f"IDX:{ticker.split('.')[0]}"
114
- elif ".T" in ticker: fdr_symbol = f"TSE:{ticker.split('.')[0]}" # 일본 FDR 포맷 보정
115
-
116
  start = (datetime.datetime.now() - datetime.timedelta(days=90)).strftime('%Y-%m-%d')
117
  hist = fdr.DataReader(fdr_symbol, start)
118
  if not hist.empty: return hist.rename(columns={'Close':'Close', 'Open':'Open', 'High':'High', 'Low':'Low'}), "FDR"
@@ -123,6 +152,10 @@ def get_chart_data(ticker):
123
  except: pass
124
  return pd.DataFrame(), "None"
125
 
 
 
 
 
126
  # μ‹œκ°ν™”
127
  def plot_candle_chart(hist, title, source):
128
  fig = go.Figure(data=[go.Candlestick(x=hist.index, open=hist['Open'], high=hist['High'], low=hist['Low'], close=hist['Close'], name="Price")])
@@ -169,59 +202,80 @@ with st.sidebar:
169
 
170
  # --- 1. AI 슀마트 검색 ---
171
  if menu == "πŸ” AI 슀마트 검색":
172
- st.subheader("🧠 무엇이든 λ¬Όμ–΄λ³΄μ„Έμš”")
173
  c1, c2 = st.columns([3, 1])
174
- with c1: query = st.text_input("검색어", "λΉ„λ‚˜λ°€ν¬", label_visibility="collapsed")
175
  with c2: btn = st.button("뢄석", use_container_width=True)
176
 
177
  if btn:
178
- with st.status("🧠 AI 가동 쀑...", expanded=True) as status:
 
179
  info = identify_target_with_ai(query)
180
  if info:
181
- name, ticker, key = info.get('name'), info.get('ticker'), info.get('search_keyword')
182
- st.info(f"νƒ€κ²Ÿ: **{name} ({ticker})** | ν‚€μ›Œλ“œ: {key}")
 
 
 
 
183
 
 
184
  h, src = get_chart_data(ticker)
185
- news = get_news(key)
 
 
 
186
 
187
  curr, pct = "N/A", 0
188
  if not h.empty:
189
  curr = h['Close'].iloc[-1]
190
- # [버그 μˆ˜μ •] 데이터가 1개뿐일 λ•Œ μ•ˆμ „ 처리
191
  if len(h) >= 2:
192
  prev = h['Close'].iloc[-2]
193
- if prev != 0:
194
- pct = ((curr - prev)/prev)*100
195
- else:
196
- pct = 0.0 # 전일 데이터가 μ—†μœΌλ©΄ 등락λ₯  0
197
-
198
  status.update(label="βœ… 뢄석 μ™„λ£Œ", state="complete", expanded=False)
199
  else:
200
  c_web, p_web, s_web = get_price_data_robust(ticker, name)
201
  if c_web:
202
  curr, pct, src = c_web, p_web, s_web
203
- status.update(label="⚠️ 차트 μ—†μŒ (μ›Ή 데이터 μ‚¬μš©)", state="complete", expanded=False)
204
  else:
205
  status.update(label="❌ 데이터 μ—†μŒ", state="complete", expanded=False)
206
 
207
  st.divider()
208
  m1, m2 = st.columns(2)
209
- m1.metric("Price", f"{curr:,.0f}" if isinstance(curr, (int, float)) else curr, f"{pct:.2f}%")
210
  m2.metric("Source", src)
211
 
212
  if not h.empty: st.plotly_chart(plot_candle_chart(h, name, src), use_container_width=True)
213
- else: st.warning(f"차트λ₯Ό 그릴 수 μ—†μŠ΅λ‹ˆλ‹€. (Source: {src})")
 
 
 
 
 
 
 
 
 
 
 
214
 
215
- with st.expander("λ‰΄μŠ€ 보기"): st.text(news)
 
216
 
217
- st.subheader(f"🧠 Insight: {name}")
218
- prompt = f"[ROLE] Analyst. [TARGET] {name} ({ticker}). [DATA] Price:{curr}, Trend:{pct:.2f}%. [NEWS] {news}. [TASK] Analyze & Verdict. [LANG] Korean."
 
 
 
 
 
219
  msg = [{"role": "user", "content": prompt}]
220
  stream = client.chat.completions.create(model="Qwen/Qwen2.5-72B-Instruct", messages=msg, stream=True)
221
  st.write_stream(parse_stream(stream))
222
  else: st.error("인식 μ‹€νŒ¨")
223
 
224
- # --- 2. κΈ€λ‘œλ²Œ μ‹œμž₯ μŠ€μΊλ„ˆ ---
225
  elif menu == "πŸ“‘ κΈ€λ‘œλ²Œ μ‹œμž₯ μŠ€μΊλ„ˆ":
226
  st.subheader("πŸ“‘ κΈ€λ‘œλ²Œ μ‹œμž₯ μ „κ΄‘νŒ")
227
  c1, c2 = st.columns([3, 1])
@@ -235,22 +289,14 @@ elif menu == "πŸ“‘ κΈ€λ‘œλ²Œ μ‹œμž₯ μŠ€μΊλ„ˆ":
235
 
236
  for i, t in enumerate(tickers):
237
  name_display = TICKER_NAMES.get(t, t)
238
- price, pct, src = get_price_data_robust(t, name_display)
239
-
240
- if price is not None:
241
- results.append({
242
- 'Name': name_display,
243
- 'Ticker': t,
244
- 'Price': price,
245
- 'Change(%)': pct,
246
- 'Source': src
247
- })
248
  bar.progress((i+1)/len(tickers))
249
 
250
  if results:
251
  df = pd.DataFrame(results).sort_values('Change(%)', ascending=False)
252
  st.plotly_chart(plot_bar_chart(df), use_container_width=True)
253
-
254
  disp_cols = ['Name', 'Ticker', 'Price', 'Change(%)', 'Source']
255
 
256
  c_up, c_down = st.columns(2)
 
20
  st.stop()
21
 
22
  # ==============================================================================
23
+ # 🧠 [μ—”μ§„ 1] AI μ§€λŠ₯ν˜• 검색 (ν˜„μ§€μ–΄ ν‚€μ›Œλ“œ 생성)
24
  # ==============================================================================
25
+ def identify_target_with_ai(user_query):
26
+ """
27
+ μ‚¬μš©μžμ˜ μž…λ ₯ -> κΈ°μ—… νŒŒμ•… -> 'μ˜μ–΄ ν‚€μ›Œλ“œ' & 'ν˜„μ§€μ–΄ ν‚€μ›Œλ“œ' 생성
28
+ """
29
+ try:
30
+ prompt = f"""
31
+ [ROLE] Financial Entity Resolver & Polyglot Linguist.
32
+ [QUERY] "{user_query}"
33
+
34
+ [TASK]
35
+ 1. Identify the company.
36
+ 2. Determine the best Ticker (Yahoo/FDR format).
37
+ 3. Generate TWO search keywords:
38
+ - 'english_keyword': Company Name + "stock news"
39
+ - 'native_keyword': Company Name + "news" in the COMPANY'S LOCAL LANGUAGE.
40
+ (e.g., Vietnam -> "Vinamilk tin tα»©c", Indonesia -> "BCA berita saham", Japan -> "γƒˆγƒ¨γ‚Ώ ζ ͺδΎ‘ ニγƒ₯γƒΌγ‚Ή")
41
+
42
+ [OUTPUT JSON]
43
+ {{
44
+ "name": "English Name",
45
+ "ticker": "TICKER",
46
+ "english_keyword": "...",
47
+ "native_keyword": "..."
48
+ }}
49
+ """
50
+ messages = [{"role": "user", "content": prompt}]
51
+ response = client.chat.completions.create(
52
+ model="Qwen/Qwen2.5-72B-Instruct", messages=messages, max_tokens=200
53
+ )
54
+ content = response.choices[0].message.content.strip()
55
+ content = re.sub(r"```json|```", "", content).strip()
56
+ return json.loads(content)
57
+ except: return None
58
+
59
+ # ==============================================================================
60
+ # πŸ•΅οΈ [μ—”μ§„ 2] λ‹€κ΅­μ–΄ λ‰΄μŠ€ μˆ˜μ§‘ (Dual Search)
61
+ # ==============================================================================
62
+ def get_polyglot_news(eng_key, native_key):
63
+ """
64
+ μ˜μ–΄ 검색결과 + ν˜„μ§€μ–΄ 검색결과λ₯Ό ν•©μ³μ„œ 리턴
65
+ """
66
+ summary = ""
67
+ seen_urls = set()
68
+
69
  try:
70
  with DDGS() as ddgs:
71
+ # 1. μ˜μ–΄ λ‰΄μŠ€ (κΈ€λ‘œλ²Œ μ‹œκ°) - 졜근 1달
72
+ results_eng = ddgs.news(eng_key, timelimit="m", max_results=3)
73
+ summary += f"=== Global News (English) ===\n"
74
+ for r in results_eng:
75
+ if r['url'] not in seen_urls:
76
+ summary += f"[{r.get('date','?')}] {r['title']}\n"
77
+ seen_urls.add(r['url'])
78
+
79
+ # 2. ν˜„μ§€μ–΄ λ‰΄μŠ€ (둜컬 이슈) - 졜근 1달
80
+ # native_keyκ°€ μ˜μ–΄λž‘ λ‹€λ₯Ό λ•Œλ§Œ μ‹€ν–‰
81
+ if eng_key != native_key:
82
+ results_native = ddgs.news(native_key, timelimit="m", max_results=4)
83
+ summary += f"\n=== Local News (Native Language) ===\n"
84
+ for r in results_native:
85
+ if r['url'] not in seen_urls:
86
+ summary += f"[{r.get('date','?')}] {r['title']}\n"
87
+ seen_urls.add(r['url'])
88
+
89
+ return summary if summary else "No recent news found."
90
+ except Exception as e:
91
+ return f"News Search Error: {e}"
92
 
93
  # ==============================================================================
94
+ # πŸ› οΈ [μ—”μ§„ 3] 데이터 μˆ˜μ§‘ (FDR/Yahoo/Web)
95
  # ==============================================================================
96
  def get_price_data_robust(ticker, name):
97
  # 1. FDR
 
104
  hist = fdr.DataReader(fdr_symbol, start=(datetime.datetime.now() - datetime.timedelta(days=10)))
105
  if not hist.empty:
106
  curr = hist['Close'].iloc[-1]
 
107
  prev = hist['Close'].iloc[-2] if len(hist) > 1 else curr
 
 
108
  pct = 0.0
109
+ if prev != 0: pct = ((curr - prev)/prev)*100
 
 
110
  return curr, pct, "FDR"
111
  except: pass
112
 
 
120
  return price, pct, "Yahoo"
121
  except: pass
122
 
123
+ # 3. Web Search (Last Resort)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  try:
125
  with DDGS() as ddgs:
126
+ # μ£Όκ°€ 검색은 μ˜μ–΄λ‘œ ν•˜λŠ”κ²Œ κ°€μž₯ νŒŒμ‹±ν•˜κΈ° 쉬움
127
+ q = f"{name} {ticker} stock price quote"
128
+ results = ddgs.text(q, max_results=2)
129
+ blob = " ".join([r['body'] for r in results])
130
+ match = re.search(r'(\d{1,3}(,\d{3})*(\.\d+)?)', blob)
131
+ if match:
132
+ price = float(match.group(0).replace(",", ""))
133
+ return price, 0.0, "Web Search"
134
+ except: pass
135
+
136
+ return None, None, "Fail"
137
 
138
+ # 차트 데이터
139
  def get_chart_data(ticker):
140
  try:
141
  fdr_symbol = ticker
142
  if ".VN" in ticker: fdr_symbol = ticker.split('.')[0]
143
  elif ".JK" in ticker: fdr_symbol = f"IDX:{ticker.split('.')[0]}"
144
+ elif ".T" in ticker: fdr_symbol = f"TSE:{ticker.split('.')[0]}"
 
145
  start = (datetime.datetime.now() - datetime.timedelta(days=90)).strftime('%Y-%m-%d')
146
  hist = fdr.DataReader(fdr_symbol, start)
147
  if not hist.empty: return hist.rename(columns={'Close':'Close', 'Open':'Open', 'High':'High', 'Low':'Low'}), "FDR"
 
152
  except: pass
153
  return pd.DataFrame(), "None"
154
 
155
+ def parse_stream(stream):
156
+ for chunk in stream:
157
+ if chunk.choices: yield chunk.choices[0].delta.content or ""
158
+
159
  # μ‹œκ°ν™”
160
  def plot_candle_chart(hist, title, source):
161
  fig = go.Figure(data=[go.Candlestick(x=hist.index, open=hist['Open'], high=hist['High'], low=hist['Low'], close=hist['Close'], name="Price")])
 
202
 
203
  # --- 1. AI 슀마트 검색 ---
204
  if menu == "πŸ” AI 슀마트 검색":
205
+ st.subheader("🧠 λ‹€κ΅­μ–΄ AI 주식 λΉ„μ„œ")
206
  c1, c2 = st.columns([3, 1])
207
+ with c1: query = st.text_input("검색어", "λ² νŠΈλ‚¨ λΉ„λ‚˜λ°€ν¬", label_visibility="collapsed")
208
  with c2: btn = st.button("뢄석", use_container_width=True)
209
 
210
  if btn:
211
+ with st.status("🧠 AIκ°€ ν˜„μ§€ μ–Έμ–΄λ‘œ 기업을 뢄석 쀑...", expanded=True) as status:
212
+ # 1. AIμ—κ²Œ ν˜„μ§€μ–΄ ν‚€μ›Œλ“œ 생성 μš”μ²­
213
  info = identify_target_with_ai(query)
214
  if info:
215
+ name = info.get('name')
216
+ ticker = info.get('ticker')
217
+ eng_key = info.get('english_keyword')
218
+ native_key = info.get('native_keyword') # μ—¬κΈ°κ°€ 핡심!
219
+
220
+ st.info(f"πŸ’‘ νƒ€κ²Ÿ: **{name} ({ticker})**\n- 🌏 κΈ€λ‘œλ²Œ 검색: '{eng_key}'\n- πŸ‡»πŸ‡³ ν˜„μ§€ 검색: **'{native_key}'**")
221
 
222
+ # 2. 데이터 μˆ˜μ§‘
223
  h, src = get_chart_data(ticker)
224
+
225
+ # 3. λ‰΄μŠ€ μˆ˜μ§‘ (μ˜μ–΄ + ν˜„μ§€μ–΄)
226
+ st.write("πŸ“° λ‹€κ΅­μ–΄ λ‰΄μŠ€ μˆ˜μ§‘ 쀑 (Polyglot Search)...")
227
+ news_data = get_polyglot_news(eng_key, native_key)
228
 
229
  curr, pct = "N/A", 0
230
  if not h.empty:
231
  curr = h['Close'].iloc[-1]
 
232
  if len(h) >= 2:
233
  prev = h['Close'].iloc[-2]
234
+ if prev != 0: pct = ((curr - prev)/prev)*100
 
 
 
 
235
  status.update(label="βœ… 뢄석 μ™„λ£Œ", state="complete", expanded=False)
236
  else:
237
  c_web, p_web, s_web = get_price_data_robust(ticker, name)
238
  if c_web:
239
  curr, pct, src = c_web, p_web, s_web
240
+ status.update(label="⚠️ 차트 μ—†μŒ (μ›Ή 데이터)", state="complete", expanded=False)
241
  else:
242
  status.update(label="❌ 데이터 μ—†μŒ", state="complete", expanded=False)
243
 
244
  st.divider()
245
  m1, m2 = st.columns(2)
246
+ m1.metric("Current Price", f"{curr:,.0f}" if isinstance(curr, (int, float)) else curr, f"{pct:.2f}%")
247
  m2.metric("Source", src)
248
 
249
  if not h.empty: st.plotly_chart(plot_candle_chart(h, name, src), use_container_width=True)
250
+ else: st.warning(f"차트 데이터 λΆ€μž¬. (Source: {src})")
251
+
252
+ with st.expander(f"πŸ“° μˆ˜μ§‘λœ λ‹€κ΅­μ–΄ λ‰΄μŠ€ 원문 ({len(news_data.splitlines())} lines)"):
253
+ st.text(news_data)
254
+
255
+ st.subheader(f"🧠 AI Insight: {name}")
256
+ # AIμ—κ²Œ λ²ˆμ—­ 및 뢄석 μ§€μ‹œ
257
+ prompt = f"""
258
+ [ROLE] Polyglot Investment Analyst (Korean/English/Vietnamese/Indonesian/etc).
259
+ [TARGET] {name} ({ticker})
260
+ [USER QUERY] "{query}"
261
+ [DATA] Price:{curr}, Trend:{pct:.2f}%
262
 
263
+ [NEWS CONTEXT (English & Local)]
264
+ {news_data}
265
 
266
+ [TASK]
267
+ 1. Translate & Summarize key local news from the context (if any).
268
+ 2. Analyze recent sentiment (3 months).
269
+ 3. Verdict (Buy/Hold/Sell).
270
+
271
+ [LANG] Korean.
272
+ """
273
  msg = [{"role": "user", "content": prompt}]
274
  stream = client.chat.completions.create(model="Qwen/Qwen2.5-72B-Instruct", messages=msg, stream=True)
275
  st.write_stream(parse_stream(stream))
276
  else: st.error("인식 μ‹€νŒ¨")
277
 
278
+ # --- 2. μ‹œμž₯ μŠ€μΊλ„ˆ ---
279
  elif menu == "πŸ“‘ κΈ€λ‘œλ²Œ μ‹œμž₯ μŠ€μΊλ„ˆ":
280
  st.subheader("πŸ“‘ κΈ€λ‘œλ²Œ μ‹œμž₯ μ „κ΄‘νŒ")
281
  c1, c2 = st.columns([3, 1])
 
289
 
290
  for i, t in enumerate(tickers):
291
  name_display = TICKER_NAMES.get(t, t)
292
+ p, c, s = get_price_data_robust(t, name_display)
293
+ if p is not None:
294
+ results.append({'Name': name_display, 'Ticker': t, 'Price': p, 'Change(%)': c, 'Source': s})
 
 
 
 
 
 
 
295
  bar.progress((i+1)/len(tickers))
296
 
297
  if results:
298
  df = pd.DataFrame(results).sort_values('Change(%)', ascending=False)
299
  st.plotly_chart(plot_bar_chart(df), use_container_width=True)
 
300
  disp_cols = ['Name', 'Ticker', 'Price', 'Change(%)', 'Source']
301
 
302
  c_up, c_down = st.columns(2)