benjamin5607 commited on
Commit
b0dbc9e
ยท
verified ยท
1 Parent(s): 3cbca0c

Update streamlit_app.py

Browse files
Files changed (1) hide show
  1. streamlit_app.py +200 -111
streamlit_app.py CHANGED
@@ -9,7 +9,7 @@ import json
9
  import datetime
10
  import re
11
  import time
12
- import random # ๐ŸŽฒ ์ธ๊ฐ„์ ์ธ ๋žœ๋ค ๋”œ๋ ˆ์ด๋ฅผ ์œ„ํ•ด ์ถ”๊ฐ€
13
 
14
  # 1. ํŽ˜์ด์ง€ ์„ค์ •
15
  st.set_page_config(page_title="Pocket Quant AI", page_icon="๐Ÿง ", layout="wide")
@@ -18,36 +18,125 @@ st.set_page_config(page_title="Pocket Quant AI", page_icon="๐Ÿง ", layout="wide"
18
  if "HF_TOKEN" in st.secrets:
19
  client = InferenceClient(api_key=st.secrets["HF_TOKEN"])
20
  else:
21
- st.error("๐Ÿšจ ์„ค์ • ์˜ค๋ฅ˜: Secrets์— 'HF_TOKEN'์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.")
22
  st.stop()
23
 
24
  # ==============================================================================
25
- # ๐Ÿ•ต๏ธ [์œ„์žฅ์ˆ ] ๊ฐ€์งœ ๋ช…ํ•จ (User-Agent)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  # ==============================================================================
27
  FAKE_HEADERS = {
28
  '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',
29
- 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
30
- 'Accept-Language': 'en-US,en;q=0.5',
31
  'Referer': 'https://www.google.com/'
32
  }
33
 
34
  # ==============================================================================
35
- # ๐Ÿ•ธ๏ธ [ํ•ต์‹ฌ ์—”์ง„] 3์ค‘ ๊ทธ๋ฌผ๋ง ๋‰ด์Šค ์ˆ˜์ง‘๊ธฐ (์‚ฌ๋žŒ์ธ ์ฒ™)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  # ==============================================================================
37
  def fetch_news_robust(keyword):
38
  summary = ""
39
  seen_urls = set()
40
  try:
41
  with DDGS() as ddgs:
42
- # 1๋‹จ๊ณ„: ์ตœ๊ทผ 1๋‹ฌ (์—„๊ฒฉ)
43
  results = list(ddgs.news(keyword, timelimit="m", max_results=3))
44
-
45
- # 2๋‹จ๊ณ„: ์—†์œผ๋ฉด ์ „์ฒด ๊ธฐ๊ฐ„ (์™„ํ™”)
46
  if not results:
47
- time.sleep(random.uniform(0.5, 1.0)) # 0.5~1์ดˆ ์‰ฌ๊ธฐ
48
  results = list(ddgs.news(keyword, max_results=3))
49
-
50
- # 3๋‹จ๊ณ„: ์›น ๋ฌธ์„œ ๊ฒ€์ƒ‰ (๋‰ด์Šคํƒญ ์ฐจ๋‹จ ์šฐํšŒ)
51
  if not results:
52
  time.sleep(random.uniform(0.5, 1.0))
53
  results = list(ddgs.text(f"{keyword} latest news", max_results=3))
@@ -57,30 +146,21 @@ def fetch_news_robust(keyword):
57
  if url not in seen_urls:
58
  date = r.get('date', 'Unknown')
59
  title = r.get('title', '')
60
- body = r.get('body', '')
61
- summary += f"[{date}] {title}: {body}\n"
62
  seen_urls.add(url)
63
-
64
  except Exception as e: return f"News Error: {e}"
65
- return summary if summary else "No news found via Deep Search."
66
 
67
  # ==============================================================================
68
- # ๐Ÿ› ๏ธ [ํ•ต์‹ฌ ์—”์ง„] ๋ฐ์ดํ„ฐ ์ˆ˜์ง‘ (์‚ฌ๋žŒ์ธ ์ฒ™ ๊ฒ€์ƒ‰ ํฌํ•จ)
69
  # ==============================================================================
70
  def scrape_price_from_web(name, ticker):
71
- """
72
- ์ตœํ›„์˜ ์ˆ˜๋‹จ: ์›น ๊ฒ€์ƒ‰์œผ๋กœ ๊ฐ€๊ฒฉ ๋œฏ์–ด์˜ค๊ธฐ
73
- """
74
  try:
75
- # DDGS๋Š” ๋‚ด๋ถ€์ ์œผ๋กœ User-Agent๋ฅผ ๊ด€๋ฆฌํ•˜์ง€๋งŒ, ๋„ˆ๋ฌด ๋น ๋ฅด๋ฉด ์ฐจ๋‹จ๋จ
76
- time.sleep(random.uniform(1.0, 2.0)) # 1~2์ดˆ ๋”œ๋ ˆ์ด (์‚ฌ๋žŒ์ฒ˜๋Ÿผ)
77
-
78
  with DDGS() as ddgs:
79
  query = f"{name} {ticker} stock price quote today"
80
  results = ddgs.text(query, max_results=2)
81
  blob = " ".join([r['body'] for r in results])
82
-
83
- # ์ˆซ์ž ์ถ”์ถœ (์‰ผํ‘œ ํฌํ•จ, ์†Œ์ˆ˜์  ํฌํ•จ)
84
  match = re.search(r'(\d{1,3}(,\d{3})*(\.\d+)?)', blob)
85
  if match:
86
  price = float(match.group(0).replace(",", ""))
@@ -89,7 +169,7 @@ def scrape_price_from_web(name, ticker):
89
  except: return None, None
90
 
91
  def get_price_data_robust(ticker, name):
92
- # 1. FDR (ํ•œ๊ตญ/๋ฒ ํŠธ๋‚จ/์ธ๋„๋„ค์‹œ์•„ ๊ฐ•๋ ฅ)
93
  try:
94
  fdr_symbol = ticker
95
  if ".VN" in ticker: fdr_symbol = ticker.split('.')[0]
@@ -105,7 +185,7 @@ def get_price_data_robust(ticker, name):
105
  return curr, pct, "FDR"
106
  except: pass
107
 
108
- # 2. Yahoo (๋ฏธ๊ตญ/์ผ๋ณธ ๊ฐ•๋ ฅ)
109
  try:
110
  stock = yf.Ticker(ticker)
111
  price = stock.fast_info.last_price
@@ -115,14 +195,30 @@ def get_price_data_robust(ticker, name):
115
  return price, pct, "Yahoo"
116
  except: pass
117
 
118
- # 3. Web Search (์‚ฌ๋žŒ์ธ ์ฒ™ ๊ฒ€์ƒ‰)
119
  price, pct = scrape_price_from_web(name, ticker)
120
- if price is not None: return price, pct, "Web Search ๐Ÿ•ต๏ธ"
121
 
122
  return None, None, "Fail"
123
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  # ==============================================================================
125
- # ๐Ÿง  [์—”์ง„] AI ์ง€๋Šฅํ˜•
126
  # ==============================================================================
127
  def identify_target_with_ai(user_query):
128
  try:
@@ -147,89 +243,54 @@ def parse_stream(stream):
147
  for chunk in stream:
148
  if chunk.choices: yield chunk.choices[0].delta.content or ""
149
 
150
- # ์ฐจํŠธ ๋ฐ์ดํ„ฐ
151
- def get_chart_data(ticker):
152
- try:
153
- fdr_symbol = ticker
154
- if ".VN" in ticker: fdr_symbol = ticker.split('.')[0]
155
- elif ".JK" in ticker: fdr_symbol = f"IDX:{ticker.split('.')[0]}"
156
- elif ".T" in ticker: fdr_symbol = f"TSE:{ticker.split('.')[0]}"
157
- start = (datetime.datetime.now() - datetime.timedelta(days=90)).strftime('%Y-%m-%d')
158
- # [์œ„์žฅ์ˆ ] requests๋ฅผ ์ง์ ‘ ์“ฐ๋Š” FDR ๋‚ด๋ถ€ ๋กœ์ง์€ ๊ฑด๋“œ๋ฆฌ๊ธฐ ํž˜๋“ค์ง€๋งŒ,
159
- # ๋Œ€๋ถ€๋ถ„ Investing.com์€ ๋ด‡ ์ฐจ๋‹จ์ด ๋œํ•จ.
160
- hist = fdr.DataReader(fdr_symbol, start)
161
- if not hist.empty: return hist.rename(columns={'Close':'Close', 'Open':'Open', 'High':'High', 'Low':'Low'}), "FDR"
162
- except: pass
163
- try:
164
- hist = yf.Ticker(ticker).history(period="3mo")
165
- if not hist.empty: return hist, "Yahoo"
166
- except: pass
167
- return pd.DataFrame(), "None"
168
-
169
  # ์‹œ๊ฐํ™”
170
  def plot_candle_chart(hist, title, source):
171
  fig = go.Figure(data=[go.Candlestick(x=hist.index, open=hist['Open'], high=hist['High'], low=hist['Low'], close=hist['Close'], name="Price")])
172
  fig.update_layout(title=f"{title} ({source})", height=350, margin=dict(l=10, r=10, t=30, b=10), template="plotly_dark", paper_bgcolor='rgba(0,0,0,0)')
173
  return fig
174
 
175
- def plot_bar_chart(df):
176
  colors = ['#00FF00' if x > 0 else '#FF0000' for x in df['Change(%)']]
177
  fig = go.Figure(go.Bar(x=df['Name'], y=df['Change(%)'], marker_color=colors, text=df['Change(%)'].apply(lambda x: f"{x:.2f}%")))
178
  fig.update_layout(title="Market Heatmap", height=350, margin=dict(l=10, r=10, t=30, b=10), template="plotly_dark", paper_bgcolor='rgba(0,0,0,0)')
179
  return fig
180
 
181
  # ==============================================================================
182
- # ๐Ÿ’พ [๋ฐ์ดํ„ฐ]
183
- # ==============================================================================
184
- TICKER_NAMES = {
185
- "AAPL": "Apple", "NVDA": "NVIDIA", "TSLA": "Tesla", "AMZN": "Amazon", "MSFT": "Microsoft",
186
- "005930.KS": "Samsung Elec", "000660.KS": "SK Hynix", "207940.KS": "Samsung Bio",
187
- "VIC.VN": "Vingroup", "VHM.VN": "Vinhomes", "VNM.VN": "Vinamilk", "VCB.VN": "Vietcombank", "GAS.VN": "PV Gas",
188
- "BBCA.JK": "BCA", "BBRI.JK": "BRI", "GOTO.JK": "GoTo", "ASII.JK": "Astra Intl",
189
- "7203.T": "Toyota", "6758.T": "Sony", "9984.T": "SoftBank",
190
- "9988.HK": "Alibaba", "0700.HK": "Tencent", "2330.TW": "TSMC",
191
- "RELIANCE.NS": "Reliance", "TCS.NS": "TCS"
192
- }
193
-
194
- MARKET_SAMPLES = {
195
- "๐Ÿ‡ป๐Ÿ‡ณ ๋ฒ ํŠธ๋‚จ (Vietnam)": ["VIC.VN", "VHM.VN", "VCB.VN", "VNM.VN", "HPG.VN", "MSN.VN", "GAS.VN"],
196
- "๐Ÿ‡ฎ๐Ÿ‡ฉ ์ธ๋„๋„ค์‹œ์•„": ["BBCA.JK", "BBRI.JK", "TLKM.JK", "BMRI.JK", "ASII.JK", "GOTO.JK"],
197
- "๐Ÿ‡ฐ๐Ÿ‡ท ํ•œ๊ตญ (Korea)": ["005930.KS", "000660.KS", "035420.KS", "035720.KS", "005380.KS", "207940.KS"],
198
- "๐Ÿ‡บ๐Ÿ‡ธ ๋ฏธ๊ตญ (USA)": ["AAPL", "NVDA", "TSLA", "AMZN", "MSFT", "GOOGL", "META", "AMD"],
199
- "๐Ÿ‡ฏ๐Ÿ‡ต ์ผ๋ณธ (Japan)": ["7203.T", "6758.T", "9984.T", "8035.T", "6861.T", "7974.T"],
200
- "๐Ÿ‡จ๐Ÿ‡ณ ์ค‘๊ตญ/ํ™์ฝฉ": ["9988.HK", "0700.HK", "3690.HK", "1211.HK", "1810.HK"],
201
- "๐Ÿ‡น๐Ÿ‡ผ ๋Œ€๋งŒ (Taiwan)": ["2330.TW", "2454.TW", "2317.TW", "2308.TW"],
202
- "๐Ÿ‡ฎ๐Ÿ‡ณ ์ธ๋„ (India)": ["RELIANCE.NS", "TCS.NS", "HDFCBANK.NS", "INFY.NS"]
203
- }
204
-
205
- # ==============================================================================
206
- # ๐Ÿ–ฅ๏ธ UI
207
  # ==============================================================================
208
  with st.sidebar:
209
- st.title("๐Ÿง  Pocket Quant AI")
 
 
 
 
 
 
210
  st.divider()
211
- menu = st.radio("MENU", ["๐Ÿ” AI ์Šค๋งˆํŠธ ๊ฒ€์ƒ‰", "๐Ÿ“ก ๊ธ€๋กœ๋ฒŒ ์‹œ์žฅ ์Šค์บ๋„ˆ"], index=0)
 
 
212
 
213
- if menu == "๐Ÿ” AI ์Šค๋งˆํŠธ ๊ฒ€์ƒ‰":
214
- st.subheader("๐Ÿง  ๋‹ค๊ตญ์–ด AI ์ฃผ์‹ ๋น„์„œ")
 
 
 
215
  c1, c2 = st.columns([3, 1])
216
- with c1: query = st.text_input("๊ฒ€์ƒ‰์–ด", "๋ฒ ํŠธ๋‚จ ๋น„๋‚˜๋ฐ€ํฌ", label_visibility="collapsed")
217
- with c2: btn = st.button("๋ถ„์„", use_container_width=True)
218
 
219
  if btn:
220
- with st.status("๐Ÿง  AI๊ฐ€ ์‚ฌ๋žŒ์ฒ˜๋Ÿผ ๊ฒ€์ƒ‰ ์ค‘...", expanded=True) as status:
221
  info = identify_target_with_ai(query)
222
  if info:
223
  name, ticker = info.get('name'), info.get('ticker')
224
  eng_key, native_key = info.get('eng_key'), info.get('native_key')
225
 
226
- st.info(f"๐Ÿ’ก ํƒ€๊ฒŸ: **{name} ({ticker})**")
227
 
228
- # ๋ฐ์ดํ„ฐ ์ˆ˜์ง‘
229
  h, src = get_chart_data(ticker)
230
-
231
- # ๋‰ด์Šค ์ˆ˜์ง‘ (์‚ฌ๋žŒ์ธ ์ฒ™ ๋”œ๋ ˆ์ด ํฌํ•จ)
232
- st.write("๐Ÿ“ฐ ๋‰ด์Šค ๊ฒ€์ƒ‰ ์ค‘...")
233
  news_data = get_polyglot_news(eng_key, native_key)
234
 
235
  curr, pct = "N/A", 0
@@ -238,38 +299,59 @@ if menu == "๐Ÿ” AI ์Šค๋งˆํŠธ ๊ฒ€์ƒ‰":
238
  if len(h) >= 2:
239
  prev = h['Close'].iloc[-2]
240
  if prev != 0: pct = ((curr - prev)/prev)*100
241
- status.update(label="โœ… ๋ถ„์„ ์™„๋ฃŒ", state="complete", expanded=False)
242
  else:
243
  c_web, p_web, s_web = get_price_data_robust(ticker, name)
244
  if c_web:
245
  curr, pct, src = c_web, p_web, s_web
246
- status.update(label="โš ๏ธ ์ฐจํŠธ ์—†์Œ (์›น ๊ฒ€์ƒ‰ ์„ฑ๊ณต)", state="complete", expanded=False)
247
  else:
248
- status.update(label="โŒ ๋ฐ์ดํ„ฐ ์—†์Œ", state="complete", expanded=False)
249
 
250
  st.divider()
251
  m1, m2 = st.columns(2)
252
- m1.metric("Current Price", f"{curr:,.0f}" if isinstance(curr, (int, float)) else curr, f"{pct:.2f}%")
253
- m2.metric("Source", src)
254
 
255
  if not h.empty: st.plotly_chart(plot_candle_chart(h, name, src), use_container_width=True)
256
- else: st.warning(f"์ฐจํŠธ ๋ฐ์ดํ„ฐ ๋ถ€์žฌ. (Source: {src})")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
257
 
258
- with st.expander("๐Ÿ“ฐ ๋‰ด์Šค ์›๋ฌธ"): st.text(news_data)
 
 
 
259
 
260
- st.subheader(f"๐Ÿง  AI Insight: {name}")
261
- prompt = f"[ROLE] Analyst. [TARGET] {name} ({ticker}). [DATA] Price:{curr}, Trend:{pct:.2f}%. [NEWS] {news_data}. [TASK] Sentiment & Verdict. [LANG] Korean."
262
  msg = [{"role": "user", "content": prompt}]
263
  stream = client.chat.completions.create(model="Qwen/Qwen2.5-72B-Instruct", messages=msg, stream=True)
264
  st.write_stream(parse_stream(stream))
265
- else: st.error("์ธ์‹ ์‹คํŒจ")
266
 
267
- elif menu == "๐Ÿ“ก ๊ธ€๋กœ๋ฒŒ ์‹œ์žฅ ์Šค์บ๋„ˆ":
268
- st.subheader("๐Ÿ“ก ๊ธ€๋กœ๋ฒŒ ์‹œ์žฅ ์ „๊ด‘ํŒ")
269
- st.caption("โ€ป ์‚ฌ๋žŒ์ฒ˜๋Ÿผ ์ฒœ์ฒœํžˆ ๊ฒ€์ƒ‰ํ•˜๋ฏ€๋กœ ์†๋„๊ฐ€ ์กฐ๊ธˆ ๋А๋ฆด ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. (์ฐจ๋‹จ ๋ฐฉ์ง€)")
 
 
 
 
270
  c1, c2 = st.columns([3, 1])
271
- with c1: target = st.selectbox("๊ตญ๊ฐ€", list(MARKET_SAMPLES.keys()))
272
- with c2: scan = st.button("์Šค์บ” ์‹œ์ž‘")
273
 
274
  if scan:
275
  tickers = MARKET_SAMPLES[target]
@@ -278,22 +360,29 @@ elif menu == "๐Ÿ“ก ๊ธ€๋กœ๋ฒŒ ์‹œ์žฅ ์Šค์บ๋„ˆ":
278
 
279
  for i, t in enumerate(tickers):
280
  name_display = TICKER_NAMES.get(t, t)
281
- # ์—ฌ๊ธฐ ๋‚ด๋ถ€์—์„œ Web Search ๋ฐœ๋™ ์‹œ ๋žœ๋ค sleep์ด ์ ์šฉ๋จ
282
  p, c, s = get_price_data_robust(t, name_display)
283
  if p is not None:
284
- results.append({'Name': name_display, 'Ticker': t, 'Price': p, 'Change(%)': c, 'Source': s})
 
 
 
 
 
 
285
  bar.progress((i+1)/len(tickers))
286
 
287
  if results:
288
  df = pd.DataFrame(results).sort_values('Change(%)', ascending=False)
289
- st.plotly_chart(plot_bar_chart(df), use_container_width=True)
 
 
 
290
 
291
- disp_cols = ['Name', 'Ticker', 'Price', 'Change(%)', 'Source']
292
  c_up, c_down = st.columns(2)
293
  with c_up:
294
- st.success("๐Ÿ”ฅ Top Gainers")
295
- st.dataframe(df.head(10)[disp_cols].style.format({"Price": "{:,.2f}", "Change(%)": "{:,.2f}%"}), use_container_width=True)
296
  with c_down:
297
- st.error("๐Ÿ’ง Top Losers")
298
- st.dataframe(df.tail(10)[disp_cols].sort_values('Change(%)').style.format({"Price": "{:,.2f}", "Change(%)": "{:,.2f}%"}), use_container_width=True)
299
- else: st.warning("๋ฐ์ดํ„ฐ ์ˆ˜์ง‘ ์‹คํŒจ")
 
9
  import datetime
10
  import re
11
  import time
12
+ import random
13
 
14
  # 1. ํŽ˜์ด์ง€ ์„ค์ •
15
  st.set_page_config(page_title="Pocket Quant AI", page_icon="๐Ÿง ", layout="wide")
 
18
  if "HF_TOKEN" in st.secrets:
19
  client = InferenceClient(api_key=st.secrets["HF_TOKEN"])
20
  else:
21
+ st.error("๐Ÿšจ HF_TOKEN required in secrets.")
22
  st.stop()
23
 
24
  # ==============================================================================
25
+ # ๐ŸŒ [UI] ๋‹ค๊ตญ์–ด ๋”•์…”๋„ˆ๋ฆฌ (Language Pack)
26
+ # ==============================================================================
27
+ UI_TEXT = {
28
+ "KR": {
29
+ "sidebar_title": "๐Ÿง  Pocket Quant AI",
30
+ "lang_label": "์–ธ์–ด ์„ค์ • (Language)",
31
+ "menu_search": "๐Ÿ” AI ์Šค๋งˆํŠธ ๊ฒ€์ƒ‰",
32
+ "menu_scanner": "๐Ÿ“ก ๊ธ€๋กœ๋ฒŒ ์‹œ์žฅ ์Šค์บ๋„ˆ",
33
+ "search_title": "๐Ÿง  ๋‹ค๊ตญ์–ด AI ์ฃผ์‹ ๋น„์„œ",
34
+ "search_placeholder": "์˜ˆ: ๋ฒ ํŠธ๋‚จ ๋น„๋‚˜๋ฐ€ํฌ, ์‚ผ์„ฑ์ „์ž...",
35
+ "btn_analyze": "๋ถ„์„ ์‹œ์ž‘",
36
+ "status_thinking": "๐Ÿง  AI๊ฐ€ ๋ถ„์„ ์ค‘์ž…๋‹ˆ๋‹ค...",
37
+ "info_target": "ํƒ€๊ฒŸ",
38
+ "info_keywords": "๊ฒ€์ƒ‰ ํ‚ค์›Œ๋“œ",
39
+ "status_news": "๐Ÿ“ฐ ๋‰ด์Šค ์ˆ˜์ง‘ ์ค‘...",
40
+ "status_chart_fail": "โš ๏ธ ์ฐจํŠธ ์—†์Œ (์›น ๊ฒ€์ƒ‰ ๋ฐ์ดํ„ฐ ์‚ฌ์šฉ)",
41
+ "status_data_fail": "โŒ ๋ฐ์ดํ„ฐ ์—†์Œ",
42
+ "metric_price": "ํ˜„์žฌ๊ฐ€",
43
+ "metric_source": "์ถœ์ฒ˜",
44
+ "expander_news": "๐Ÿ“ฐ ๋‰ด์Šค ์›๋ฌธ ๋ณด๊ธฐ",
45
+ "insight_title": "๐Ÿง  AI ํˆฌ์ž ๋ฆฌํฌํŠธ",
46
+ "scanner_title": "๐Ÿ“ก ๊ธ€๋กœ๋ฒŒ ์‹œ์žฅ ์ „๊ด‘ํŒ",
47
+ "scanner_caption": "โ€ป ์‚ฌ๋žŒ์ฒ˜๋Ÿผ ์ฒœ์ฒœํžˆ ์ •๋ฐ€ ๊ฒ€์ƒ‰ํ•ฉ๋‹ˆ๋‹ค. (์†๋„: ๋А๋ฆผ)",
48
+ "btn_scan": "์Šค์บ” ์‹œ์ž‘",
49
+ "tab_gainers": "๐Ÿ”ฅ ๊ธ‰๋“ฑ (Top Gainers)",
50
+ "tab_losers": "๐Ÿ’ง ๊ธ‰๋ฝ (Top Losers)",
51
+ "col_name": "๊ธฐ์—…๋ช…",
52
+ "col_price": "๊ฐ€๊ฒฉ",
53
+ "col_change": "๋“ฑ๋ฝ๋ฅ ",
54
+ "col_source": "์ถœ์ฒ˜",
55
+ "msg_fail": "๋ฐ์ดํ„ฐ ์ˆ˜์ง‘ ์‹คํŒจ",
56
+ "llm_lang_instruction": "Korean" # ํ”„๋กฌํ”„ํŠธ์šฉ
57
+ },
58
+ "EN": {
59
+ "sidebar_title": "๐Ÿง  Pocket Quant AI",
60
+ "lang_label": "Language Settings",
61
+ "menu_search": "๐Ÿ” AI Smart Search",
62
+ "menu_scanner": "๐Ÿ“ก Global Market Scanner",
63
+ "search_title": "๐Ÿง  AI Stock Assistant",
64
+ "search_placeholder": "e.g. Vinamilk, Samsung Electronics...",
65
+ "btn_analyze": "Analyze",
66
+ "status_thinking": "๐Ÿง  AI is analyzing...",
67
+ "info_target": "Target",
68
+ "info_keywords": "Keywords",
69
+ "status_news": "๐Ÿ“ฐ Fetching news...",
70
+ "status_chart_fail": "โš ๏ธ No Chart (Using Web Data)",
71
+ "status_data_fail": "โŒ No Data Found",
72
+ "metric_price": "Price",
73
+ "metric_source": "Source",
74
+ "expander_news": "๐Ÿ“ฐ View Source News",
75
+ "insight_title": "๐Ÿง  AI Investment Report",
76
+ "scanner_title": "๐Ÿ“ก Global Market Scanner",
77
+ "scanner_caption": "โ€ป Deep search with human-like delay. (Speed: Slow)",
78
+ "btn_scan": "Start Scan",
79
+ "tab_gainers": "๐Ÿ”ฅ Top Gainers",
80
+ "tab_losers": "๐Ÿ’ง Top Losers",
81
+ "col_name": "Company",
82
+ "col_price": "Price",
83
+ "col_change": "Change(%)",
84
+ "col_source": "Source",
85
+ "msg_fail": "Data collection failed",
86
+ "llm_lang_instruction": "English" # ํ”„๋กฌํ”„ํŠธ์šฉ
87
+ }
88
+ }
89
+
90
+ # ==============================================================================
91
+ # ๐Ÿ•ต๏ธ [์œ„์žฅ์ˆ ] ๊ฐ€์งœ ๋ช…ํ•จ
92
  # ==============================================================================
93
  FAKE_HEADERS = {
94
  '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',
 
 
95
  'Referer': 'https://www.google.com/'
96
  }
97
 
98
  # ==============================================================================
99
+ # ๐Ÿ’พ [๋ฐ์ดํ„ฐ] ํ‹ฐ์ปค ๋งคํ•‘
100
+ # ==============================================================================
101
+ TICKER_NAMES = {
102
+ "VIC.VN": "Vingroup", "VHM.VN": "Vinhomes", "VCB.VN": "Vietcombank", "VNM.VN": "Vinamilk",
103
+ "HPG.VN": "Hoa Phat", "MSN.VN": "Masan Group", "GAS.VN": "PV Gas",
104
+ "BBCA.JK": "BCA Bank", "BBRI.JK": "BRI Bank", "TLKM.JK": "Telkom Indo", "BMRI.JK": "Mandiri",
105
+ "ASII.JK": "Astra Intl", "GOTO.JK": "GoTo Group",
106
+ "005930.KS": "Samsung Elec", "000660.KS": "SK Hynix", "035420.KS": "NAVER", "035720.KS": "Kakao",
107
+ "005380.KS": "Hyundai Motor", "207940.KS": "Samsung Bio",
108
+ "AAPL": "Apple", "NVDA": "NVIDIA", "TSLA": "Tesla", "AMZN": "Amazon", "MSFT": "Microsoft",
109
+ "GOOGL": "Google", "META": "Meta", "AMD": "AMD",
110
+ "7203.T": "Toyota", "6758.T": "Sony", "9984.T": "SoftBank", "8035.T": "Tokyo Elec",
111
+ "6861.T": "Keyence", "7974.T": "Nintendo",
112
+ "9988.HK": "Alibaba", "0700.HK": "Tencent", "3690.HK": "Meituan", "1211.HK": "BYD", "1810.HK": "Xiaomi",
113
+ "2330.TW": "TSMC", "2454.TW": "MediaTek", "2317.TW": "Foxconn", "2308.TW": "Delta Elec",
114
+ "RELIANCE.NS": "Reliance Ind", "TCS.NS": "TCS", "HDFCBANK.NS": "HDFC Bank", "INFY.NS": "Infosys"
115
+ }
116
+
117
+ MARKET_SAMPLES = {
118
+ "๐Ÿ‡ป๐Ÿ‡ณ Vietnam": ["VIC.VN", "VHM.VN", "VCB.VN", "VNM.VN", "HPG.VN", "MSN.VN", "GAS.VN"],
119
+ "๐Ÿ‡ฎ๐Ÿ‡ฉ Indonesia": ["BBCA.JK", "BBRI.JK", "TLKM.JK", "BMRI.JK", "ASII.JK", "GOTO.JK"],
120
+ "๐Ÿ‡ฐ๐Ÿ‡ท Korea": ["005930.KS", "000660.KS", "035420.KS", "035720.KS", "005380.KS", "207940.KS"],
121
+ "๐Ÿ‡บ๐Ÿ‡ธ USA": ["AAPL", "NVDA", "TSLA", "AMZN", "MSFT", "GOOGL", "META", "AMD"],
122
+ "๐Ÿ‡ฏ๐Ÿ‡ต Japan": ["7203.T", "6758.T", "9984.T", "8035.T", "6861.T", "7974.T"],
123
+ "๐Ÿ‡จ๐Ÿ‡ณ China/HK": ["9988.HK", "0700.HK", "3690.HK", "1211.HK", "1810.HK"],
124
+ "๐Ÿ‡น๐Ÿ‡ผ Taiwan": ["2330.TW", "2454.TW", "2317.TW", "2308.TW"],
125
+ "๐Ÿ‡ฎ๐Ÿ‡ณ India": ["RELIANCE.NS", "TCS.NS", "HDFCBANK.NS", "INFY.NS"]
126
+ }
127
+
128
+ # ==============================================================================
129
+ # ๐Ÿ•ธ๏ธ [ํ•ต์‹ฌ ์—”์ง„] ๋‰ด์Šค ์ˆ˜์ง‘
130
  # ==============================================================================
131
  def fetch_news_robust(keyword):
132
  summary = ""
133
  seen_urls = set()
134
  try:
135
  with DDGS() as ddgs:
 
136
  results = list(ddgs.news(keyword, timelimit="m", max_results=3))
 
 
137
  if not results:
138
+ time.sleep(random.uniform(0.5, 1.0))
139
  results = list(ddgs.news(keyword, max_results=3))
 
 
140
  if not results:
141
  time.sleep(random.uniform(0.5, 1.0))
142
  results = list(ddgs.text(f"{keyword} latest news", max_results=3))
 
146
  if url not in seen_urls:
147
  date = r.get('date', 'Unknown')
148
  title = r.get('title', '')
149
+ summary += f"[{date}] {title}\n"
 
150
  seen_urls.add(url)
 
151
  except Exception as e: return f"News Error: {e}"
152
+ return summary if summary else "No news found."
153
 
154
  # ==============================================================================
155
+ # ๐Ÿ› ๏ธ [ํ•ต์‹ฌ ์—”์ง„] ๊ฐ€๊ฒฉ ๋ฐ์ดํ„ฐ ์ˆ˜์ง‘
156
  # ==============================================================================
157
  def scrape_price_from_web(name, ticker):
 
 
 
158
  try:
159
+ time.sleep(random.uniform(1.0, 1.5))
 
 
160
  with DDGS() as ddgs:
161
  query = f"{name} {ticker} stock price quote today"
162
  results = ddgs.text(query, max_results=2)
163
  blob = " ".join([r['body'] for r in results])
 
 
164
  match = re.search(r'(\d{1,3}(,\d{3})*(\.\d+)?)', blob)
165
  if match:
166
  price = float(match.group(0).replace(",", ""))
 
169
  except: return None, None
170
 
171
  def get_price_data_robust(ticker, name):
172
+ # 1. FDR
173
  try:
174
  fdr_symbol = ticker
175
  if ".VN" in ticker: fdr_symbol = ticker.split('.')[0]
 
185
  return curr, pct, "FDR"
186
  except: pass
187
 
188
+ # 2. Yahoo
189
  try:
190
  stock = yf.Ticker(ticker)
191
  price = stock.fast_info.last_price
 
195
  return price, pct, "Yahoo"
196
  except: pass
197
 
198
+ # 3. Web Search
199
  price, pct = scrape_price_from_web(name, ticker)
200
+ if price is not None: return price, pct, "Web Search"
201
 
202
  return None, None, "Fail"
203
 
204
+ def get_chart_data(ticker):
205
+ try:
206
+ fdr_symbol = ticker
207
+ if ".VN" in ticker: fdr_symbol = ticker.split('.')[0]
208
+ elif ".JK" in ticker: fdr_symbol = f"IDX:{ticker.split('.')[0]}"
209
+ elif ".T" in ticker: fdr_symbol = f"TSE:{ticker.split('.')[0]}"
210
+ start = (datetime.datetime.now() - datetime.timedelta(days=90)).strftime('%Y-%m-%d')
211
+ hist = fdr.DataReader(fdr_symbol, start)
212
+ if not hist.empty: return hist.rename(columns={'Close':'Close', 'Open':'Open', 'High':'High', 'Low':'Low'}), "FDR"
213
+ except: pass
214
+ try:
215
+ hist = yf.Ticker(ticker).history(period="3mo")
216
+ if not hist.empty: return hist, "Yahoo"
217
+ except: pass
218
+ return pd.DataFrame(), "None"
219
+
220
  # ==============================================================================
221
+ # ๐Ÿง  [์—”์ง„] AI ๊ฒ€์ƒ‰
222
  # ==============================================================================
223
  def identify_target_with_ai(user_query):
224
  try:
 
243
  for chunk in stream:
244
  if chunk.choices: yield chunk.choices[0].delta.content or ""
245
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
246
  # ์‹œ๊ฐํ™”
247
  def plot_candle_chart(hist, title, source):
248
  fig = go.Figure(data=[go.Candlestick(x=hist.index, open=hist['Open'], high=hist['High'], low=hist['Low'], close=hist['Close'], name="Price")])
249
  fig.update_layout(title=f"{title} ({source})", height=350, margin=dict(l=10, r=10, t=30, b=10), template="plotly_dark", paper_bgcolor='rgba(0,0,0,0)')
250
  return fig
251
 
252
+ def plot_bar_chart(df, lang_cols):
253
  colors = ['#00FF00' if x > 0 else '#FF0000' for x in df['Change(%)']]
254
  fig = go.Figure(go.Bar(x=df['Name'], y=df['Change(%)'], marker_color=colors, text=df['Change(%)'].apply(lambda x: f"{x:.2f}%")))
255
  fig.update_layout(title="Market Heatmap", height=350, margin=dict(l=10, r=10, t=30, b=10), template="plotly_dark", paper_bgcolor='rgba(0,0,0,0)')
256
  return fig
257
 
258
  # ==============================================================================
259
+ # ๐Ÿ–ฅ๏ธ UI & Sidebar (๋‹ค๊ตญ์–ด ์ ์šฉ)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
260
  # ==============================================================================
261
  with st.sidebar:
262
+ # 1. ์–ธ์–ด ์„ ํƒ (Language Selector)
263
+ lang_code = st.selectbox("Language / ์–ธ์–ด", ["KR", "EN"])
264
+
265
+ # ํ…์ŠคํŠธ ๋กœ๋”ฉ
266
+ T = UI_TEXT[lang_code]
267
+
268
+ st.title(T['sidebar_title'])
269
  st.divider()
270
+
271
+ # ๋ฉ”๋‰ด ์ด๋ฆ„๋„ ์–ธ์–ด์— ๋”ฐ๋ผ ๋ณ€๊ฒฝ
272
+ menu = st.radio("MENU", [T['menu_search'], T['menu_scanner']], index=0)
273
 
274
+ # ==============================================================================
275
+ # ๋ชจ๋“œ 1: AI ์Šค๋งˆํŠธ ๊ฒ€์ƒ‰
276
+ # ==============================================================================
277
+ if menu == T['menu_search']:
278
+ st.subheader(T['search_title'])
279
  c1, c2 = st.columns([3, 1])
280
+ with c1: query = st.text_input("Query", placeholder=T['search_placeholder'], label_visibility="collapsed")
281
+ with c2: btn = st.button(T['btn_analyze'], use_container_width=True)
282
 
283
  if btn:
284
+ with st.status(T['status_thinking'], expanded=True) as status:
285
  info = identify_target_with_ai(query)
286
  if info:
287
  name, ticker = info.get('name'), info.get('ticker')
288
  eng_key, native_key = info.get('eng_key'), info.get('native_key')
289
 
290
+ st.info(f"๐Ÿ’ก {T['info_target']}: **{name} ({ticker})**")
291
 
 
292
  h, src = get_chart_data(ticker)
293
+ st.write(T['status_news'])
 
 
294
  news_data = get_polyglot_news(eng_key, native_key)
295
 
296
  curr, pct = "N/A", 0
 
299
  if len(h) >= 2:
300
  prev = h['Close'].iloc[-2]
301
  if prev != 0: pct = ((curr - prev)/prev)*100
302
+ status.update(label="โœ… OK", state="complete", expanded=False)
303
  else:
304
  c_web, p_web, s_web = get_price_data_robust(ticker, name)
305
  if c_web:
306
  curr, pct, src = c_web, p_web, s_web
307
+ status.update(label=T['status_chart_fail'], state="complete", expanded=False)
308
  else:
309
+ status.update(label=T['status_data_fail'], state="complete", expanded=False)
310
 
311
  st.divider()
312
  m1, m2 = st.columns(2)
313
+ m1.metric(T['metric_price'], f"{curr:,.0f}" if isinstance(curr, (int, float)) else curr, f"{pct:.2f}%")
314
+ m2.metric(T['metric_source'], src)
315
 
316
  if not h.empty: st.plotly_chart(plot_candle_chart(h, name, src), use_container_width=True)
317
+ else: st.warning(f"Chart N/A ({src})")
318
+
319
+ with st.expander(T['expander_news']): st.text(news_data)
320
+
321
+ st.subheader(T['insight_title'])
322
+
323
+ # [์ค‘์š”] ์‚ฌ์šฉ์ž๊ฐ€ ์„ ํƒํ•œ ์–ธ์–ด(T['llm_lang_instruction'])๋ฅผ ํ”„๋กฌํ”„ํŠธ์— ์ฃผ์ž…
324
+ target_lang = T['llm_lang_instruction']
325
+
326
+ prompt = f"""
327
+ [ROLE] Global Investment Analyst.
328
+ [TARGET] {name} ({ticker})
329
+ [USER QUERY] "{query}"
330
+ [DATA] Price:{curr}, Trend:{pct:.2f}%.
331
+ [NEWS CONTEXT] {news_data}
332
 
333
+ [TASK]
334
+ 1. Summarize situation.
335
+ 2. Analyze sentiment.
336
+ 3. Verdict (Buy/Hold/Sell).
337
 
338
+ [OUTPUT LANGUAGE] **{target_lang}** (Strictly output in {target_lang})
339
+ """
340
  msg = [{"role": "user", "content": prompt}]
341
  stream = client.chat.completions.create(model="Qwen/Qwen2.5-72B-Instruct", messages=msg, stream=True)
342
  st.write_stream(parse_stream(stream))
343
+ else: st.error("AI Error")
344
 
345
+ # ==============================================================================
346
+ # ๋ชจ๋“œ 2: ๊ธ€๋กœ๋ฒŒ ์‹œ์žฅ ์Šค์บ๋„ˆ
347
+ # ==============================================================================
348
+ elif menu == T['menu_scanner']:
349
+ st.subheader(T['scanner_title'])
350
+ st.caption(T['scanner_caption'])
351
+
352
  c1, c2 = st.columns([3, 1])
353
+ with c1: target = st.selectbox("Market", list(MARKET_SAMPLES.keys()), label_visibility="collapsed")
354
+ with c2: scan = st.button(T['btn_scan'])
355
 
356
  if scan:
357
  tickers = MARKET_SAMPLES[target]
 
360
 
361
  for i, t in enumerate(tickers):
362
  name_display = TICKER_NAMES.get(t, t)
 
363
  p, c, s = get_price_data_robust(t, name_display)
364
  if p is not None:
365
+ results.append({
366
+ T['col_name']: name_display,
367
+ 'Ticker': t,
368
+ T['col_price']: p,
369
+ 'Change(%)': c,
370
+ T['col_source']: s
371
+ })
372
  bar.progress((i+1)/len(tickers))
373
 
374
  if results:
375
  df = pd.DataFrame(results).sort_values('Change(%)', ascending=False)
376
+ st.plotly_chart(plot_bar_chart(df, T), use_container_width=True)
377
+
378
+ # ๋‹ค๊ตญ์–ด ์ปฌ๋Ÿผ๋ช… ์ ์šฉ
379
+ disp_cols = [T['col_name'], 'Ticker', T['col_price'], 'Change(%)', T['col_source']]
380
 
 
381
  c_up, c_down = st.columns(2)
382
  with c_up:
383
+ st.success(T['tab_gainers'])
384
+ st.dataframe(df.head(10)[disp_cols].style.format({T['col_price']: "{:,.2f}", "Change(%)": "{:,.2f}%"}), use_container_width=True)
385
  with c_down:
386
+ st.error(T['tab_losers'])
387
+ st.dataframe(df.tail(10)[disp_cols].sort_values('Change(%)').style.format({T['col_price']: "{:,.2f}", "Change(%)": "{:,.2f}%"}), use_container_width=True)
388
+ else: st.warning(T['msg_fail'])