benjamin5607 commited on
Commit
135647f
ยท
verified ยท
1 Parent(s): 823fb3d

Update streamlit_app.py

Browse files
Files changed (1) hide show
  1. streamlit_app.py +129 -150
streamlit_app.py CHANGED
@@ -22,28 +22,25 @@ else:
22
  st.stop()
23
 
24
  # ==============================================================================
25
- # ๐ŸŒ [UI] ๋‹ค๊ตญ์–ด ๋”•์…”๋„ˆ๋ฆฌ (๋ฌธ๊ตฌ ์ˆ˜์ • ์™„๋ฃŒ)
26
  # ==============================================================================
27
  UI_TEXT = {
28
  "KR": {
29
  "sidebar_title": "๐Ÿง  Pocket Quant AI",
30
- "menu_search": "๐Ÿ” AI ์Šค๋งˆํŠธ ๊ฒ€์ƒ‰",
31
  "menu_scanner": "๐Ÿ“ก ๊ธ€๋กœ๋ฒŒ ์‹œ์žฅ ์Šค์บ๋„ˆ",
32
- "search_title": "๐Ÿง  ๋‹ค๊ตญ์–ด AI ์ฃผ์‹ ๋น„์„œ",
33
- "search_placeholder": "์˜ˆ: ๋ฒ ํŠธ๋‚จ ์บ‰๋””์—”, ๋ฏธ๊ตญ ํŒ”๋ž€ํ‹ฐ์–ด...",
34
  "btn_analyze": "๋ถ„์„ ์‹œ์ž‘",
35
- "status_thinking": "๐Ÿง  AI๊ฐ€ ๋ถ„์„ ์ค‘์ž…๋‹ˆ๋‹ค...",
36
- "info_target": "ํƒ€๊ฒŸ",
37
  "status_news": "๐Ÿ“ฐ ๋‰ด์Šค ์ˆ˜์ง‘ ์ค‘...",
38
- "status_chart_fail": "โš ๏ธ ์ฐจํŠธ ์—†์Œ (์›น ๊ฒ€์ƒ‰ ๋ฐ์ดํ„ฐ ์‚ฌ์šฉ)",
39
- "status_data_fail": "โŒ ๋ฐ์ดํ„ฐ ์—†์Œ",
40
  "metric_price": "ํ˜„์žฌ๊ฐ€",
41
  "metric_source": "์ถœ์ฒ˜",
42
  "expander_news": "๐Ÿ“ฐ ๋‰ด์Šค ์›๋ฌธ ๋ณด๊ธฐ",
43
- "insight_title": "๐Ÿง  AI ํˆฌ์ž ๋ฆฌํฌํŠธ",
44
  "scanner_title": "๐Ÿ“ก ๊ธ€๋กœ๋ฒŒ ์‹œ์žฅ ์ „๊ด‘ํŒ (Max 100)",
45
- "scanner_caption": "โ€ป ์•ฝ 100๊ฐœ ๊ธฐ์—…์„ ๋ถ„์„ํ•˜์—ฌ ์ƒ์œ„ 10๊ฐœ๋ฅผ ์„ ๋ณ„ํ•ฉ๋‹ˆ๋‹ค.", # ์ˆ˜์ •๋จ
46
- "btn_scan": "100๊ฐœ ์ข…๋ชฉ ์Šค์บ” ์‹œ์ž‘", # ์ˆ˜์ •๋จ
47
  "tab_gainers": "๐Ÿ”ฅ ๊ธ‰๋“ฑ Top 10 (์ƒ์Šน์žฅ)",
48
  "tab_losers": "๐Ÿ’ง ๊ธ‰๋ฝ Top 10 (ํ•˜๋ฝ์žฅ)",
49
  "col_name": "๊ธฐ์—…๋ช…",
@@ -55,23 +52,20 @@ UI_TEXT = {
55
  },
56
  "EN": {
57
  "sidebar_title": "๐Ÿง  Pocket Quant AI",
58
- "menu_search": "๐Ÿ” AI Smart Search",
59
  "menu_scanner": "๐Ÿ“ก Global Market Scanner",
60
- "search_title": "๐Ÿง  AI Stock Assistant",
61
- "search_placeholder": "e.g. Vinamilk, Palantir...",
62
  "btn_analyze": "Analyze",
63
- "status_thinking": "๐Ÿง  AI is analyzing...",
64
- "info_target": "Target",
65
  "status_news": "๐Ÿ“ฐ Fetching news...",
66
- "status_chart_fail": "โš ๏ธ No Chart (Using Web Data)",
67
- "status_data_fail": "โŒ No Data Found",
68
  "metric_price": "Price",
69
  "metric_source": "Source",
70
  "expander_news": "๐Ÿ“ฐ View Source News",
71
- "insight_title": "๐Ÿง  AI Investment Report",
72
  "scanner_title": "๐Ÿ“ก Global Market Scanner (Max 100)",
73
- "scanner_caption": "โ€ป Analyzing 100 companies to show Top 10.", # ์ˆ˜์ •๋จ
74
- "btn_scan": "Scan 100 Stocks", # ์ˆ˜์ •๋จ
75
  "tab_gainers": "๐Ÿ”ฅ Top 10 Gainers",
76
  "tab_losers": "๐Ÿ’ง Top 10 Losers",
77
  "col_name": "Company",
@@ -84,88 +78,35 @@ UI_TEXT = {
84
  }
85
 
86
  # ==============================================================================
87
- # ๐Ÿ’พ [๋ฐ์ดํ„ฐ] ๋Œ€๊ทœ๋ชจ ํ™•์žฅ ํ‹ฐ์ปค (์•ฝ 100๊ฐœ ๊ทœ๋ชจ)
88
  # ==============================================================================
 
89
  TICKER_NAMES = {
90
- # ๐Ÿ‡ป๐Ÿ‡ณ ๋ฒ ํŠธ๋‚จ
91
  "VIC.VN": "Vingroup", "VHM.VN": "Vinhomes", "VCB.VN": "Vietcombank", "VNM.VN": "Vinamilk",
92
- "HPG.VN": "Hoa Phat", "MSN.VN": "Masan Group", "GAS.VN": "PV Gas", "NVL.VN": "Novaland",
93
- "PDR.VN": "Phat Dat", "DIG.VN": "DIC Corp", "CEO.VN": "CEO Group", "SSI.VN": "SSI Sec",
94
- "VND.VN": "VNDirect", "MWG.VN": "Mobile World", "FRT.VN": "FPT Retail", "FPT.VN": "FPT Corp",
95
- "STB.VN": "Sacombank", "MBB.VN": "MB Bank", "TCB.VN": "Techcombank", "VPB.VN": "VPBank",
96
- "VRE.VN": "Vincom Retail", "DGC.VN": "Duc Giang Chem", "VHC.VN": "Vinh Hoan", "KBC.VN": "Kinh Bac",
97
- "GVR.VN": "Vietnam Rubber", "SAB.VN": "Sabeco", "BID.VN": "BIDV", "CTG.VN": "VietinBank",
98
-
99
- # ๐Ÿ‡ฎ๐Ÿ‡ฉ ์ธ๋„๋„ค์‹œ์•„
100
- "BBCA.JK": "BCA Bank", "BBRI.JK": "BRI Bank", "TLKM.JK": "Telkom", "BMRI.JK": "Mandiri",
101
- "ASII.JK": "Astra Intl", "GOTO.JK": "GoTo", "UNVR.JK": "Unilever", "ADRO.JK": "Adaro Energy",
102
- "MDKA.JK": "Merdeka Copper", "ANTM.JK": "Aneka Tambang", "ICBP.JK": "Indofood CBP",
103
- "KLBF.JK": "Kalbe Farma", "BUKA.JK": "Bukalapak", "PGAS.JK": "Perusahaan Gas",
104
-
105
- # ๐Ÿ‡ฐ๐Ÿ‡ท ํ•œ๊ตญ
106
- "005930.KS": "Samsung Elec", "000660.KS": "SK Hynix", "035420.KS": "NAVER", "035720.KS": "Kakao",
107
- "005380.KS": "Hyundai Motor", "207940.KS": "Samsung Bio", "068270.KS": "Celltrion",
108
- "086520.KQ": "Ecopro", "247540.KQ": "Ecopro BM", "005490.KS": "POSCO Holdings", "010120.KS": "LS ELECTRIC",
109
- "012450.KS": "Hanwha Aero", "042700.KS": "Hanmi Semi", "196170.KQ": "Alteogen",
110
- "352820.KS": "HYBE", "035900.KQ": "JYP Ent", "000270.KS": "Kia", "010950.KS": "S-Oil",
111
- "032830.KQ": "Samsung Life", "329180.KS": "Hyundai Heavy", "015760.KS": "KEPCO",
112
-
113
- # ๐Ÿ‡บ๐Ÿ‡ธ ๋ฏธ๊ตญ
114
  "AAPL": "Apple", "NVDA": "NVIDIA", "TSLA": "Tesla", "AMZN": "Amazon", "MSFT": "Microsoft",
115
  "GOOGL": "Google", "META": "Meta", "AMD": "AMD", "NFLX": "Netflix", "INTC": "Intel",
116
- "PLTR": "Palantir", "COIN": "Coinbase", "U": "Unity", "RBLX": "Roblox", "SOFI": "SoFi",
117
- "PYPL": "PayPal", "SQ": "Block", "UBER": "Uber", "ABNB": "Airbnb", "HOOD": "Robinhood",
118
- "LLY": "Eli Lilly", "NVO": "Novo Nordisk", "PFE": "Pfizer", "MRK": "Merck",
119
- "XOM": "Exxon", "CVX": "Chevron", "KO": "Coca-Cola", "PEP": "Pepsi", "COST": "Costco",
120
- "DIS": "Disney", "NKE": "Nike", "SBUX": "Starbucks", "MCD": "McDonalds",
121
-
122
- # ๐Ÿ‡ฏ๐Ÿ‡ต ์ผ๋ณธ
123
  "7203.T": "Toyota", "6758.T": "Sony", "9984.T": "SoftBank", "8035.T": "Tokyo Elec",
124
- "6861.T": "Keyence", "7974.T": "Nintendo", "8306.T": "MUFG", "6501.T": "Hitachi",
125
- "8058.T": "Mitsubishi", "8001.T": "Itochu", "8031.T": "Mitsui", "6920.T": "Lasertec",
126
- "4063.T": "Shin-Etsu", "7741.T": "HOYA", "6146.T": "Disco", "7267.T": "Honda",
127
-
128
- # ๐Ÿ‡จ๐Ÿ‡ณ ์ค‘๊ตญ/ํ™์ฝฉ/๋Œ€๋งŒ/์ธ๋„
129
- "9988.HK": "Alibaba", "0700.HK": "Tencent", "3690.HK": "Meituan", "1211.HK": "BYD",
130
- "1810.HK": "Xiaomi", "0941.HK": "China Mobile", "9888.HK": "Baidu", "9618.HK": "JD.com",
131
- "2015.HK": "Li Auto", "9868.HK": "Xpeng", "0981.HK": "SMIC",
132
- "2330.TW": "TSMC", "2454.TW": "MediaTek", "2317.TW": "Foxconn", "2308.TW": "Delta Elec",
133
- "RELIANCE.NS": "Reliance", "TCS.NS": "TCS", "HDFCBANK.NS": "HDFC Bank", "INFY.NS": "Infosys"
134
  }
135
-
136
- # ์Šค์บ” ๋Œ€์ƒ ๋ฆฌ์ŠคํŠธ (ํ‚ค ๊ฐ’์— 'Max 100' ๋ช…์‹œ ์™„๋ฃŒ)
137
  MARKET_SAMPLES = {
138
- "๐Ÿ‡ป๐Ÿ‡ณ Vietnam (Max 100)": [
139
- "VIC.VN", "VHM.VN", "VRE.VN", "VNM.VN", "MSN.VN", "GAS.VN", "HPG.VN", "HSG.VN",
140
- "NVL.VN", "PDR.VN", "DIG.VN", "CEO.VN", "DXG.VN", "KBC.VN", "GVR.VN",
141
- "VCB.VN", "TCB.VN", "VPB.VN", "MBB.VN", "STB.VN", "ACB.VN", "BID.VN", "CTG.VN",
142
- "SSI.VN", "VND.VN", "VCI.VN", "MWG.VN", "FRT.VN", "DGW.VN", "FPT.VN", "DGC.VN", "VHC.VN", "SAB.VN"
143
- ],
144
- "๐Ÿ‡บ๐Ÿ‡ธ USA (Max 100)": [
145
- "AAPL", "MSFT", "GOOGL", "AMZN", "NVDA", "META", "TSLA", "AMD", "INTC", "QCOM",
146
- "AVGO", "MU", "PLTR", "COIN", "U", "RBLX", "SOFI", "UBER", "ABNB", "HOOD", "PYPL", "SQ",
147
- "LLY", "NVO", "JNJ", "PFE", "MRK", "UNH", "XOM", "CVX", "JPM", "V", "MA",
148
- "KO", "PEP", "COST", "WMT", "DIS", "NKE", "SBUX", "MCD"
149
- ],
150
- "๐Ÿ‡ฐ๐Ÿ‡ท Korea (Max 100)": [
151
- "005930.KS", "000660.KS", "005380.KS", "000270.KS", "035420.KS", "035720.KS",
152
- "005490.KS", "086520.KQ", "247540.KQ", "010120.KS", "207940.KS", "068270.KS",
153
- "196170.KQ", "012450.KS", "042700.KS", "352820.KS", "010950.KS", "032830.KQ", "329180.KS", "015760.KS"
154
- ],
155
- "๐Ÿ‡ฎ๐Ÿ‡ฉ Indonesia (Max 50)": ["BBCA.JK", "BBRI.JK", "BMRI.JK", "BBNI.JK", "TLKM.JK", "ASII.JK", "GOTO.JK", "ADRO.JK", "MDKA.JK", "ANTM.JK", "UNVR.JK", "ICBP.JK", "KLBF.JK", "BUKA.JK", "PGAS.JK"],
156
- "๐Ÿ‡ฏ๐Ÿ‡ต Japan (Max 50)": ["7203.T", "6758.T", "9984.T", "8035.T", "6861.T", "7974.T", "8306.T", "6501.T", "8058.T", "8001.T", "8031.T", "6920.T", "4063.T", "7741.T", "6146.T", "7267.T"],
157
- "๐Ÿ‡จ๐Ÿ‡ณ China/HK (Max 50)": ["9988.HK", "0700.HK", "3690.HK", "1211.HK", "1810.HK", "0941.HK", "9888.HK", "9618.HK", "2015.HK", "9868.HK", "0981.HK"],
158
  "๐Ÿ‡น๐Ÿ‡ผ Taiwan (Max 30)": ["2330.TW", "2454.TW", "2317.TW", "2308.TW", "2603.TW", "2881.TW", "1301.TW"],
159
- "๐Ÿ‡ฎ๐Ÿ‡ณ India (Max 30)": ["RELIANCE.NS", "TCS.NS", "HDFCBANK.NS", "INFY.NS", "ICICIBANK.NS", "TATAMOTORS.NS", "BHARTIARTL.NS"]
160
  }
161
 
162
  # ==============================================================================
163
- # ๐Ÿ› ๏ธ [์—”์ง„] ๋ฐ์ดํ„ฐ ์ˆ˜์ง‘ ํ•จ์ˆ˜๋“ค
164
  # ==============================================================================
165
- FAKE_HEADERS = {
166
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
167
- 'Referer': 'https://www.google.com/'
168
- }
169
 
170
  def fetch_news_robust(keyword):
171
  summary = ""
@@ -202,7 +143,6 @@ def scrape_price_from_web(name, ticker):
202
  return None, None
203
 
204
  def get_price_data_robust(ticker, name):
205
- # FDR
206
  try:
207
  fdr_symbol = ticker
208
  if ".VN" in ticker: fdr_symbol = ticker.split('.')[0]
@@ -216,14 +156,12 @@ def get_price_data_robust(ticker, name):
216
  if prev != 0: pct = ((curr - prev)/prev)*100
217
  return curr, pct, "FDR"
218
  except: pass
219
- # Yahoo
220
  try:
221
  stock = yf.Ticker(ticker)
222
  price = stock.fast_info.last_price
223
  prev = stock.fast_info.previous_close
224
  if price and prev: return price, ((price - prev)/prev)*100, "Yahoo"
225
  except: pass
226
- # Web
227
  price, pct = scrape_price_from_web(name, ticker)
228
  if price is not None: return price, pct, "Web"
229
  return None, None, "Fail"
@@ -244,17 +182,29 @@ def get_chart_data(ticker):
244
  except: pass
245
  return pd.DataFrame(), "None"
246
 
247
- def identify_target_with_ai(user_query):
 
 
 
248
  try:
249
  prompt = f"""
250
- [ROLE] Entity Resolver. [QUERY] "{user_query}"
251
- [OUTPUT JSON] {{ "name": "Eng Name", "ticker": "TICKER", "eng_key": "Name stock news", "native_key": "Local Name + news keyword" }}
 
 
 
 
 
 
 
 
 
252
  """
253
  messages = [{"role": "user", "content": prompt}]
254
- response = client.chat.completions.create(model="Qwen/Qwen2.5-72B-Instruct", messages=messages, max_tokens=200)
255
  content = re.sub(r"```json|```", "", response.choices[0].message.content.strip()).strip()
256
  return json.loads(content)
257
- except: return None
258
 
259
  def get_polyglot_news(eng_key, native_key):
260
  return f"Global:\n{fetch_news_robust(eng_key)}\nLocal:\n{fetch_news_robust(native_key)}"
@@ -285,6 +235,7 @@ with st.sidebar:
285
  st.divider()
286
  menu = st.radio("MENU", [T['menu_search'], T['menu_scanner']], index=0)
287
 
 
288
  if menu == T['menu_search']:
289
  st.subheader(T['search_title'])
290
  c1, c2 = st.columns([3, 1])
@@ -293,53 +244,91 @@ if menu == T['menu_search']:
293
 
294
  if btn:
295
  with st.status(T['status_thinking'], expanded=True) as status:
296
- info = identify_target_with_ai(query)
297
- if info:
298
- name, ticker = info.get('name'), info.get('ticker')
299
- eng_key, native_key = info.get('eng_key'), info.get('native_key')
300
- st.info(f"๐Ÿ’ก {T['info_target']}: **{name} ({ticker})**")
301
-
302
- h, src = get_chart_data(ticker)
303
- st.write(T['status_news'])
304
- news_data = get_polyglot_news(eng_key, native_key)
305
-
306
- curr, pct = "N/A", 0
307
- if not h.empty:
308
- curr = h['Close'].iloc[-1]
309
- if len(h) >= 2:
310
- prev = h['Close'].iloc[-2]
311
- if prev != 0: pct = ((curr - prev)/prev)*100
312
- status.update(label="โœ… OK", state="complete", expanded=False)
313
- else:
314
- c_web, p_web, s_web = get_price_data_robust(ticker, name)
315
- if c_web:
316
- curr, pct, src = c_web, p_web, s_web
317
- status.update(label=T['status_chart_fail'], state="complete", expanded=False)
318
- else:
319
- status.update(label=T['status_data_fail'], state="complete", expanded=False)
320
 
321
- st.divider()
322
- m1, m2 = st.columns(2)
323
- m1.metric(T['metric_price'], f"{curr:,.0f}" if isinstance(curr, (int, float)) else curr, f"{pct:.2f}%")
324
- m2.metric(T['metric_source'], src)
325
 
326
- if not h.empty: st.plotly_chart(plot_candle_chart(h, name, src), use_container_width=True)
327
- else: st.warning(f"Chart N/A ({src})")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
328
 
329
- with st.expander(T['expander_news']): st.text(news_data)
330
 
 
 
331
  st.subheader(T['insight_title'])
 
332
  target_lang = T['llm_lang_instruction']
 
 
333
  prompt = f"""
334
- [ROLE] Analyst. [TARGET] {name} ({ticker}). [QUERY] "{query}"
335
- [DATA] Price:{curr}, Trend:{pct:.2f}%. [NEWS] {news_data}
336
- [TASK] Summarize, Sentiment, Verdict. [LANG] {target_lang}.
 
 
 
 
 
 
 
 
337
  """
338
  msg = [{"role": "user", "content": prompt}]
339
  stream = client.chat.completions.create(model="Qwen/Qwen2.5-72B-Instruct", messages=msg, stream=True)
340
  st.write_stream(parse_stream(stream))
341
- else: st.error("AI Error")
 
342
 
 
343
  elif menu == T['menu_scanner']:
344
  st.subheader(T['scanner_title'])
345
  st.caption(T['scanner_caption'])
@@ -352,15 +341,12 @@ elif menu == T['menu_scanner']:
352
  tickers = MARKET_SAMPLES[target]
353
  results = []
354
  bar = st.progress(0)
355
- status_text = st.empty()
356
 
357
- status_text.text("๐Ÿš€ Phase 1: Batch Speed Scan...")
358
- try:
359
- batch_data = yf.download(tickers, period="5d", progress=False)['Close']
360
  except: batch_data = pd.DataFrame()
361
-
362
- status_text.text("๐Ÿ•ต๏ธ Phase 2: Deep Robust Scan...")
363
 
 
364
  for i, t in enumerate(tickers):
365
  name_display = TICKER_NAMES.get(t, t)
366
  p, c, s = None, None, None
@@ -379,16 +365,11 @@ elif menu == T['menu_scanner']:
379
 
380
  if p is not None:
381
  results.append({
382
- T['col_name']: name_display,
383
- 'Ticker': t,
384
- T['col_price']: p,
385
- 'Change(%)': c,
386
- T['col_source']: s
387
  })
388
  bar.progress((i+1)/len(tickers))
389
 
390
- status_text.empty()
391
-
392
  if results:
393
  df = pd.DataFrame(results).sort_values('Change(%)', ascending=False)
394
  st.plotly_chart(plot_bar_chart(df, T), use_container_width=True)
@@ -401,12 +382,10 @@ elif menu == T['menu_scanner']:
401
  c_up, c_down = st.columns(2)
402
  with c_up:
403
  st.success(T['tab_gainers'])
404
- if not df_gainers.empty:
405
- st.dataframe(df_gainers[disp_cols].style.format({T['col_price']: "{:,.2f}", "Change(%)": "{:,.2f}%"}), use_container_width=True)
406
  else: st.info("No gainers.")
407
  with c_down:
408
  st.error(T['tab_losers'])
409
- if not df_losers.empty:
410
- st.dataframe(df_losers[disp_cols].style.format({T['col_price']: "{:,.2f}", "Change(%)": "{:,.2f}%"}), use_container_width=True)
411
  else: st.info("No losers.")
412
  else: st.warning(T['msg_fail'])
 
22
  st.stop()
23
 
24
  # ==============================================================================
25
+ # ๐ŸŒ [UI] ๋‹ค๊ตญ์–ด ๋”•์…”๋„ˆ๋ฆฌ
26
  # ==============================================================================
27
  UI_TEXT = {
28
  "KR": {
29
  "sidebar_title": "๐Ÿง  Pocket Quant AI",
30
+ "menu_search": "๐Ÿ” AI ์Šค๋งˆํŠธ ๊ฒ€์ƒ‰ (๋ฉ€ํ‹ฐ)",
31
  "menu_scanner": "๐Ÿ“ก ๊ธ€๋กœ๋ฒŒ ์‹œ์žฅ ์Šค์บ๋„ˆ",
32
+ "search_title": "๐Ÿง  ๋‹ค๊ตญ์–ด AI ์ฃผ์‹ ๋น„์„œ (๋ฉ€ํ‹ฐ ํƒ€๊ฒŸ)",
33
+ "search_placeholder": "์˜ˆ: ์‚ผ์„ฑ์ „์ž๋ž‘ TSMC ๋น„๊ตํ•ด์ค˜, ๋ฒ ํŠธ๋‚จ ๋นˆ๊ทธ๋ฃน ๋ถ„์„ํ•ด์ค˜...",
34
  "btn_analyze": "๋ถ„์„ ์‹œ์ž‘",
35
+ "status_thinking": "๐Ÿง  AI๊ฐ€ ์—ฌ๋Ÿฌ ๊ธฐ์—…์„ ๋™์‹œ์— ๋ถ„์„ ์ค‘์ž…๋‹ˆ๋‹ค...",
 
36
  "status_news": "๐Ÿ“ฐ ๋‰ด์Šค ์ˆ˜์ง‘ ์ค‘...",
 
 
37
  "metric_price": "ํ˜„์žฌ๊ฐ€",
38
  "metric_source": "์ถœ์ฒ˜",
39
  "expander_news": "๐Ÿ“ฐ ๋‰ด์Šค ์›๋ฌธ ๋ณด๊ธฐ",
40
+ "insight_title": "๐Ÿง  AI ์ข…ํ•ฉ ๋ถ„์„ ๋ฆฌํฌํŠธ",
41
  "scanner_title": "๐Ÿ“ก ๊ธ€๋กœ๋ฒŒ ์‹œ์žฅ ์ „๊ด‘ํŒ (Max 100)",
42
+ "scanner_caption": "โ€ป ์•ฝ 100๊ฐœ ๊ธฐ์—…์„ ๋ถ„์„ํ•˜์—ฌ ์ƒ์œ„ 10๊ฐœ๋ฅผ ์„ ๋ณ„ํ•ฉ๋‹ˆ๋‹ค.",
43
+ "btn_scan": "100๊ฐœ ์ข…๋ชฉ ์Šค์บ” ์‹œ์ž‘",
44
  "tab_gainers": "๐Ÿ”ฅ ๊ธ‰๋“ฑ Top 10 (์ƒ์Šน์žฅ)",
45
  "tab_losers": "๐Ÿ’ง ๊ธ‰๋ฝ Top 10 (ํ•˜๋ฝ์žฅ)",
46
  "col_name": "๊ธฐ์—…๋ช…",
 
52
  },
53
  "EN": {
54
  "sidebar_title": "๐Ÿง  Pocket Quant AI",
55
+ "menu_search": "๐Ÿ” AI Smart Search (Multi)",
56
  "menu_scanner": "๐Ÿ“ก Global Market Scanner",
57
+ "search_title": "๐Ÿง  AI Stock Assistant (Multi-Target)",
58
+ "search_placeholder": "e.g. Compare Samsung and TSMC...",
59
  "btn_analyze": "Analyze",
60
+ "status_thinking": "๐Ÿง  AI is analyzing multiple targets...",
 
61
  "status_news": "๐Ÿ“ฐ Fetching news...",
 
 
62
  "metric_price": "Price",
63
  "metric_source": "Source",
64
  "expander_news": "๐Ÿ“ฐ View Source News",
65
+ "insight_title": "๐Ÿง  AI Comprehensive Report",
66
  "scanner_title": "๐Ÿ“ก Global Market Scanner (Max 100)",
67
+ "scanner_caption": "โ€ป Analyzing 100 companies to show Top 10.",
68
+ "btn_scan": "Scan 100 Stocks",
69
  "tab_gainers": "๐Ÿ”ฅ Top 10 Gainers",
70
  "tab_losers": "๐Ÿ’ง Top 10 Losers",
71
  "col_name": "Company",
 
78
  }
79
 
80
  # ==============================================================================
81
+ # ๐Ÿ’พ [๋ฐ์ดํ„ฐ] ํ‹ฐ์ปค ๋งคํ•‘ (์Šค์บ๋„ˆ์šฉ) - ๊ฒ€์ƒ‰์€ AI๊ฐ€ ์•Œ์•„์„œ ํ•จ
82
  # ==============================================================================
83
+ # (์Šค์บ๋„ˆ์šฉ ๋ฆฌ์ŠคํŠธ๋Š” ๊ธฐ์กด ์œ ์ง€ - ๋„ˆ๋ฌด ๊ธธ์–ด์„œ ์ƒ๋žตํ•˜์ง€ ์•Š๊ณ  ๊ทธ๋Œ€๋กœ ๋‘ก๋‹ˆ๋‹ค)
84
  TICKER_NAMES = {
 
85
  "VIC.VN": "Vingroup", "VHM.VN": "Vinhomes", "VCB.VN": "Vietcombank", "VNM.VN": "Vinamilk",
86
+ "HPG.VN": "Hoa Phat", "MSN.VN": "Masan Group", "GAS.VN": "PV Gas", "NVL.VN": "Novaland",
87
+ "BBCA.JK": "BCA Bank", "BBRI.JK": "BRI Bank", "TLKM.JK": "Telkom", "GOTO.JK": "GoTo",
88
+ "005930.KS": "Samsung Elec", "000660.KS": "SK Hynix", "035420.KS": "NAVER", "207940.KS": "Samsung Bio",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  "AAPL": "Apple", "NVDA": "NVIDIA", "TSLA": "Tesla", "AMZN": "Amazon", "MSFT": "Microsoft",
90
  "GOOGL": "Google", "META": "Meta", "AMD": "AMD", "NFLX": "Netflix", "INTC": "Intel",
 
 
 
 
 
 
 
91
  "7203.T": "Toyota", "6758.T": "Sony", "9984.T": "SoftBank", "8035.T": "Tokyo Elec",
92
+ "9988.HK": "Alibaba", "0700.HK": "Tencent", "2330.TW": "TSMC", "RELIANCE.NS": "Reliance"
 
 
 
 
 
 
 
 
 
93
  }
94
+ # (์Šค์บ๋„ˆ์šฉ MARKET_SAMPLES๋„ ๊ธฐ์กด ์ฝ”๋“œ ์œ ์ง€)
 
95
  MARKET_SAMPLES = {
96
+ "๐Ÿ‡ป๐Ÿ‡ณ Vietnam (Max 100)": ["VIC.VN", "VHM.VN", "VCB.VN", "VNM.VN", "HPG.VN", "MSN.VN", "GAS.VN", "NVL.VN", "PDR.VN", "DIG.VN", "SSI.VN", "VND.VN", "MWG.VN", "FRT.VN", "FPT.VN", "STB.VN", "TCB.VN", "VPB.VN", "VRE.VN", "DGC.VN"],
97
+ "๐Ÿ‡บ๐Ÿ‡ธ USA (Max 100)": ["AAPL", "NVDA", "TSLA", "AMZN", "MSFT", "GOOGL", "META", "AMD", "INTC", "PLTR", "COIN", "U", "RBLX", "SOFI", "PYPL", "SQ", "UBER", "LLY", "NVO", "JNJ", "PFE", "MRK", "XOM", "CVX", "KO", "PEP", "COST", "DIS"],
98
+ "๐Ÿ‡ฐ๐Ÿ‡ท Korea (Max 100)": ["005930.KS", "000660.KS", "005380.KS", "000270.KS", "035420.KS", "035720.KS", "005490.KS", "086520.KQ", "247540.KQ", "207940.KS", "068270.KS", "196170.KQ", "012450.KS", "352820.KS", "032830.KQ"],
99
+ "๐Ÿ‡ฎ๐Ÿ‡ฉ Indonesia (Max 50)": ["BBCA.JK", "BBRI.JK", "BMRI.JK", "BBNI.JK", "TLKM.JK", "ASII.JK", "GOTO.JK", "ADRO.JK", "MDKA.JK", "UNVR.JK", "ICBP.JK"],
100
+ "๐Ÿ‡ฏ๐Ÿ‡ต Japan (Max 50)": ["7203.T", "6758.T", "9984.T", "8035.T", "6861.T", "7974.T", "8306.T", "6501.T", "8058.T", "6920.T"],
101
+ "๐Ÿ‡จ๐Ÿ‡ณ China/HK (Max 50)": ["9988.HK", "0700.HK", "3690.HK", "1211.HK", "1810.HK", "0941.HK", "9888.HK", "9618.HK"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
  "๐Ÿ‡น๐Ÿ‡ผ Taiwan (Max 30)": ["2330.TW", "2454.TW", "2317.TW", "2308.TW", "2603.TW", "2881.TW", "1301.TW"],
103
+ "๐Ÿ‡ฎ๐Ÿ‡ณ India (Max 30)": ["RELIANCE.NS", "TCS.NS", "HDFCBANK.NS", "INFY.NS", "ICICIBANK.NS", "TATAMOTORS.NS"]
104
  }
105
 
106
  # ==============================================================================
107
+ # ๐Ÿ› ๏ธ [์—”์ง„] ๋ฐ์ดํ„ฐ ์ˆ˜์ง‘ ํ•จ์ˆ˜๋“ค (Robust)
108
  # ==============================================================================
109
+ FAKE_HEADERS = {'User-Agent': 'Mozilla/5.0 ...'}
 
 
 
110
 
111
  def fetch_news_robust(keyword):
112
  summary = ""
 
143
  return None, None
144
 
145
  def get_price_data_robust(ticker, name):
 
146
  try:
147
  fdr_symbol = ticker
148
  if ".VN" in ticker: fdr_symbol = ticker.split('.')[0]
 
156
  if prev != 0: pct = ((curr - prev)/prev)*100
157
  return curr, pct, "FDR"
158
  except: pass
 
159
  try:
160
  stock = yf.Ticker(ticker)
161
  price = stock.fast_info.last_price
162
  prev = stock.fast_info.previous_close
163
  if price and prev: return price, ((price - prev)/prev)*100, "Yahoo"
164
  except: pass
 
165
  price, pct = scrape_price_from_web(name, ticker)
166
  if price is not None: return price, pct, "Web"
167
  return None, None, "Fail"
 
182
  except: pass
183
  return pd.DataFrame(), "None"
184
 
185
+ # ==============================================================================
186
+ # ๐Ÿง  [์—”์ง„ 1] ๋ฉ€ํ‹ฐ ํƒ€๊ฒŸ AI ์ธ์‹๊ธฐ (ํ•ต์‹ฌ ์—…๊ทธ๋ ˆ์ด๋“œ)
187
+ # ==============================================================================
188
+ def identify_targets_with_ai(user_query):
189
  try:
190
  prompt = f"""
191
+ [ROLE] Financial Entity Resolver. [QUERY] "{user_query}"
192
+ [TASK]
193
+ 1. Identify ALL companies mentioned in the query. (e.g., "Samsung vs Apple" -> 2 companies)
194
+ 2. If no specific company is mentioned but a sector is (e.g., "Vietnam Banks"), pick top 2-3 representative companies.
195
+ 3. For EACH company, determine Name, Ticker, English Keyword, Native Keyword.
196
+
197
+ [OUTPUT JSON LIST]
198
+ [
199
+ {{ "name": "Eng Name 1", "ticker": "TICKER1", "eng_key": "...", "native_key": "..." }},
200
+ {{ "name": "Eng Name 2", "ticker": "TICKER2", "eng_key": "...", "native_key": "..." }}
201
+ ]
202
  """
203
  messages = [{"role": "user", "content": prompt}]
204
+ response = client.chat.completions.create(model="Qwen/Qwen2.5-72B-Instruct", messages=messages, max_tokens=300)
205
  content = re.sub(r"```json|```", "", response.choices[0].message.content.strip()).strip()
206
  return json.loads(content)
207
+ except: return []
208
 
209
  def get_polyglot_news(eng_key, native_key):
210
  return f"Global:\n{fetch_news_robust(eng_key)}\nLocal:\n{fetch_news_robust(native_key)}"
 
235
  st.divider()
236
  menu = st.radio("MENU", [T['menu_search'], T['menu_scanner']], index=0)
237
 
238
+ # --- 1. AI ๋ฉ€ํ‹ฐ ์Šค๋งˆํŠธ ๊ฒ€์ƒ‰ ---
239
  if menu == T['menu_search']:
240
  st.subheader(T['search_title'])
241
  c1, c2 = st.columns([3, 1])
 
244
 
245
  if btn:
246
  with st.status(T['status_thinking'], expanded=True) as status:
247
+ # 1. ๋‹ค์ค‘ ํƒ€๊ฒŸ ์ธ์‹
248
+ targets = identify_targets_with_ai(query)
249
+
250
+ if targets:
251
+ collected_data = [] # AI ๋ถ„์„์šฉ ํ†ตํ•ฉ ๋ฐ์ดํ„ฐ
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
252
 
253
+ # ํƒญ ์ƒ์„ฑ (๊ธฐ์—… ์ˆ˜๋งŒํผ)
254
+ tab_names = [t.get('name', 'Unknown') for t in targets]
255
+ tabs = st.tabs(tab_names)
 
256
 
257
+ for i, target in enumerate(targets):
258
+ name = target.get('name')
259
+ ticker = target.get('ticker')
260
+ eng_key = target.get('eng_key')
261
+ native_key = target.get('native_key')
262
+
263
+ with tabs[i]:
264
+ st.info(f"๐Ÿ“ **{name} ({ticker})**")
265
+
266
+ # ๋ฐ์ดํ„ฐ ์ˆ˜์ง‘
267
+ h, src = get_chart_data(ticker)
268
+ news_data = get_polyglot_news(eng_key, native_key)
269
+
270
+ curr, pct = "N/A", 0
271
+ has_data = False
272
+
273
+ if not h.empty:
274
+ curr = h['Close'].iloc[-1]
275
+ if len(h) >= 2:
276
+ prev = h['Close'].iloc[-2]
277
+ if prev != 0: pct = ((curr - prev)/prev)*100
278
+ has_data = True
279
+ else:
280
+ # ์ฐจํŠธ ์—†์œผ๋ฉด ์›น ๊ฐ€๊ฒฉ ์‹œ๋„
281
+ c_web, p_web, s_web = get_price_data_robust(ticker, name)
282
+ if c_web:
283
+ curr, pct, src = c_web, p_web, s_web
284
+ has_data = True
285
+
286
+ # UI ํ‘œ์‹œ
287
+ m1, m2 = st.columns(2)
288
+ m1.metric(T['metric_price'], f"{curr:,.0f}" if isinstance(curr, (int, float)) else curr, f"{pct:.2f}%")
289
+ m2.metric(T['metric_source'], src)
290
+
291
+ if not h.empty: st.plotly_chart(plot_candle_chart(h, name, src), use_container_width=True)
292
+ else: st.warning(f"Chart N/A")
293
+
294
+ with st.expander(T['expander_news']): st.text(news_data)
295
+
296
+ # AI ๋ถ„์„์šฉ ๋ฐ์ดํ„ฐ ์ถ•์ 
297
+ collected_data.append(f"""
298
+ [TARGET {i+1}] {name} ({ticker})
299
+ - Price: {curr}, Change: {pct:.2f}%
300
+ - News Summary: {news_data[:500]}...
301
+ """)
302
 
303
+ status.update(label="โœ… ๋ถ„์„ ์™„๋ฃŒ", state="complete", expanded=False)
304
 
305
+ # 3. ์ข…ํ•ฉ ๋ถ„์„ ๋ฆฌํฌํŠธ
306
+ st.divider()
307
  st.subheader(T['insight_title'])
308
+
309
  target_lang = T['llm_lang_instruction']
310
+ context_str = "\n".join(collected_data)
311
+
312
  prompt = f"""
313
+ [ROLE] Global Investment Analyst.
314
+ [USER QUERY] "{query}"
315
+ [COLLECTED DATA OF MULTIPLE TARGETS]
316
+ {context_str}
317
+
318
+ [TASK]
319
+ 1. Provide a synthesized analysis or comparison based on the user's query.
320
+ 2. If multiple companies, compare their recent sentiment and performance.
321
+ 3. Provide investment verdicts for each.
322
+
323
+ [OUTPUT LANGUAGE] **{target_lang}** (Strictly output in {target_lang})
324
  """
325
  msg = [{"role": "user", "content": prompt}]
326
  stream = client.chat.completions.create(model="Qwen/Qwen2.5-72B-Instruct", messages=msg, stream=True)
327
  st.write_stream(parse_stream(stream))
328
+
329
+ else: st.error("AI๊ฐ€ ๊ธฐ์—…์„ ์ฐพ์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค.")
330
 
331
+ # --- 2. ์‹œ์žฅ ์Šค์บ๋„ˆ ---
332
  elif menu == T['menu_scanner']:
333
  st.subheader(T['scanner_title'])
334
  st.caption(T['scanner_caption'])
 
341
  tickers = MARKET_SAMPLES[target]
342
  results = []
343
  bar = st.progress(0)
 
344
 
345
+ # Phase 1: Batch
346
+ try: batch_data = yf.download(tickers, period="5d", progress=False)['Close']
 
347
  except: batch_data = pd.DataFrame()
 
 
348
 
349
+ # Phase 2: Loop
350
  for i, t in enumerate(tickers):
351
  name_display = TICKER_NAMES.get(t, t)
352
  p, c, s = None, None, None
 
365
 
366
  if p is not None:
367
  results.append({
368
+ T['col_name']: name_display, 'Ticker': t,
369
+ T['col_price']: p, 'Change(%)': c, T['col_source']: s
 
 
 
370
  })
371
  bar.progress((i+1)/len(tickers))
372
 
 
 
373
  if results:
374
  df = pd.DataFrame(results).sort_values('Change(%)', ascending=False)
375
  st.plotly_chart(plot_bar_chart(df, T), use_container_width=True)
 
382
  c_up, c_down = st.columns(2)
383
  with c_up:
384
  st.success(T['tab_gainers'])
385
+ if not df_gainers.empty: st.dataframe(df_gainers[disp_cols].style.format({T['col_price']: "{:,.2f}", "Change(%)": "{:,.2f}%"}), use_container_width=True)
 
386
  else: st.info("No gainers.")
387
  with c_down:
388
  st.error(T['tab_losers'])
389
+ if not df_losers.empty: st.dataframe(df_losers[disp_cols].style.format({T['col_price']: "{:,.2f}", "Change(%)": "{:,.2f}%"}), use_container_width=True)
 
390
  else: st.info("No losers.")
391
  else: st.warning(T['msg_fail'])