benjamin5607 commited on
Commit
7251564
ยท
verified ยท
1 Parent(s): a8bbcce

Update streamlit_app.py

Browse files
Files changed (1) hide show
  1. streamlit_app.py +185 -115
streamlit_app.py CHANGED
@@ -11,80 +11,62 @@ import re
11
 
12
  # 1. ํŽ˜์ด์ง€ ์„ค์ •
13
  st.set_page_config(page_title="Pocket Quant AI", page_icon="๐Ÿง ", layout="wide")
14
- st.title("๐Ÿง  ์ง„์งœ AI ์ฃผ์‹ ๋น„์„œ")
15
- st.caption("์‚ฌ์šฉ์ž์˜ ์˜๋„๋ฅผ ๋จผ์ € ํŒŒ์•…ํ•˜๊ณ  -> ์ตœ์ ์˜ ๊ฒ€์ƒ‰์–ด๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ์ฐพ์Šต๋‹ˆ๋‹ค.")
16
 
17
  # 2. ํ† ํฐ ํ™•์ธ
18
  if "HF_TOKEN" in st.secrets:
19
  client = InferenceClient(api_key=st.secrets["HF_TOKEN"])
20
  else:
21
- st.error("๐Ÿšจ HF_TOKEN ์„ค์ • ํ•„์š”")
22
  st.stop()
23
 
24
- # --- [ํ•ต์‹ฌ ์—”์ง„] 1๋‹จ๊ณ„: AI๊ฐ€ ๋จผ์ € '๋ฌด์—‡์„ ์ฐพ์„์ง€' ํŒ๋‹จํ•˜๋Š” ํ•จ์ˆ˜ ---
 
 
25
  def identify_target_with_ai(user_query):
26
  """
27
- ์‚ฌ์šฉ์ž์˜ ์ž…๋ ฅ(์–ด๋–ค ์–ธ์–ด๋“ )์„ ๋ฐ›์•„์„œ
28
- 1. ์ •ํ™•ํ•œ ๊ธฐ์—… ์˜๋ฌธ๋ช…
29
- 2. ์•ผํ›„/FDR ํ‹ฐ์ปค
30
- 3. ๋‰ด์Šค ๊ฒ€์ƒ‰์šฉ ์ตœ์  ํ‚ค์›Œ๋“œ(์˜์–ด)
31
- ๋ฅผ JSON์œผ๋กœ ๋ฆฌํ„ด๋ฐ›์Šต๋‹ˆ๋‹ค.
32
  """
33
  try:
34
  prompt = f"""
35
- [ROLE]
36
- You are a Financial Entity Resolver. Your job is to identify the company from the user's query and prepare search parameters.
37
-
38
- [USER QUERY]
39
- "{user_query}"
40
-
41
  [TASK]
42
- 1. Identify the company clearly. (e.g., "๋น„๋‚˜๋ฐ€ํฌ" -> "Vinamilk", "๋ฒ ํŠธ๋‚จ ์ฐจ 1๋“ฑ" -> "VinFast" or "Truong Hai")
43
- 2. Find the best Ticker Symbol. Prefer Yahoo Finance format.
44
- - Vietnam: Ends with .VN (e.g., VNM.VN, VIC.VN)
45
- - Indonesia: Ends with .JK (e.g., BBCA.JK)
46
- - Korea: .KS or .KQ
47
- - Japan: .T
48
- - USA: Ticker only (e.g., AAPL)
49
- 3. Create a specific ENGLISH search keyword for news (to avoid unrelated results like NVIDIA).
50
 
51
- [OUTPUT FORMAT]
52
- Return ONLY a JSON object. No markdown. No explanations.
53
  {{
54
- "name": "Official English Company Name",
55
  "ticker": "TICKER",
56
- "search_keyword": "Company Name + 'stock business news' (e.g., 'Vinamilk Vietnam stock business')"
57
  }}
58
  """
59
-
60
  messages = [{"role": "user", "content": prompt}]
61
  response = client.chat.completions.create(
62
  model="Qwen/Qwen2.5-72B-Instruct", messages=messages, max_tokens=150
63
  )
64
-
65
- # JSON ํŒŒ์‹ฑ (AI๊ฐ€ ๊ฐ€๋” ```json ๋“ฑ์„ ๋ถ™์ผ ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ ์ œ๊ฑฐ)
66
  content = response.choices[0].message.content.strip()
67
  content = re.sub(r"```json|```", "", content).strip()
68
  return json.loads(content)
69
-
70
- except Exception as e:
71
- st.error(f"AI ํŒ๋‹จ ์‹คํŒจ: {e}")
72
- return None
73
 
74
- # --- [ํ•ต์‹ฌ ์—”์ง„] 2๋‹จ๊ณ„: ๋ฐ์ดํ„ฐ ์ˆ˜์ง‘ (FDR + Yahoo) ---
 
 
75
  def get_market_data(ticker):
76
- # 1. Yahoo ์‹œ๋„
77
  try:
78
  stock = yf.Ticker(ticker)
79
  hist = stock.history(period="3mo")
80
  if not hist.empty: return hist, "Yahoo Finance"
81
  except: pass
82
 
83
- # 2. FDR ์‹œ๋„ (Yahoo ์‹คํŒจ์‹œ)
84
  try:
85
- # FDR์šฉ ์‹ฌ๋ณผ ๋ณ€ํ™˜
86
  fdr_symbol = ticker
87
- if ".VN" in ticker: fdr_symbol = ticker.split('.')[0] # ๋ฒ ํŠธ๋‚จ
88
  elif ".JK" in ticker: fdr_symbol = f"IDX:{ticker.split('.')[0]}"
89
  elif ".T" in ticker: fdr_symbol = f"TSE:{ticker.split('.')[0]}"
90
 
@@ -94,106 +76,194 @@ def get_market_data(ticker):
94
  hist = hist.rename(columns={'Close':'Close', 'Open':'Open', 'High':'High', 'Low':'Low', 'Volume':'Volume'})
95
  return hist, "FinanceDataReader"
96
  except: pass
97
-
98
  return pd.DataFrame(), "None"
99
 
100
- # --- [ํ•ต์‹ฌ ์—”์ง„] 3๋‹จ๊ณ„: ๋‰ด์Šค ๊ฒ€์ƒ‰ (AI๊ฐ€ ์ค€ ํ‚ค์›Œ๋“œ๋กœ ์ˆ˜ํ–‰) ---
101
  def get_news(keyword):
102
  summary = ""
103
  try:
104
  with DDGS() as ddgs:
105
- # AI๊ฐ€ ๋งŒ๋“ค์–ด์ค€ '์ตœ์ ์˜ ์˜์–ด ํ‚ค์›Œ๋“œ'๋กœ ๊ฒ€์ƒ‰ -> ์ •ํ™•๋„ ์ƒ์Šน
106
  results = ddgs.news(keyword, timelimit="m", max_results=5)
107
  for r in results:
108
  summary += f"[{r.get('date','?')}] {r['title']}\n"
109
- return summary if summary else "No recent news found."
110
- except: return "Search Error"
111
 
112
  def parse_stream(stream):
113
  for chunk in stream:
114
  if chunk.choices: yield chunk.choices[0].delta.content or ""
115
 
116
- # --- ์ฐจํŠธ ๊ทธ๋ฆฌ๊ธฐ ---
117
- def plot_chart(hist, name, source):
 
 
118
  fig = go.Figure(data=[go.Candlestick(x=hist.index, open=hist['Open'], high=hist['High'], low=hist['Low'], close=hist['Close'], name="Price")])
119
- fig.update_layout(title=f"{name} ({source})", height=350, margin=dict(l=10, r=10, t=30, b=10), template="plotly_dark", paper_bgcolor='rgba(0,0,0,0)')
 
 
 
 
 
 
120
  return fig
121
 
122
  # ==============================================================================
123
- # ๋ฉ”์ธ ๋กœ์ง
124
  # ==============================================================================
125
- col1, col2 = st.columns([3, 1])
126
- with col1:
127
- # ํžŒํŠธ๋ฅผ ์ฃผ์ง€ ์•Š์Œ. AI๊ฐ€ ์•Œ์•„์„œ ํ•ด์•ผ ํ•จ.
128
- user_query = st.text_input("๊ถ๊ธˆํ•œ ๊ธฐ์—…์„ ์ž…๋ ฅํ•˜์„ธ์š” (์˜ˆ: ๋น„๋‚˜๋ฐ€ํฌ, ๋ฒ ํŠธ๋‚จ ๋นˆ๊ทธ๋ฃน, ์ผ๋ณธ ๋„์š”ํƒ€...)", "๋น„๋‚˜๋ฐ€ํฌ")
129
- with col2:
130
- btn = st.button("๋ถ„์„ ์‹œ์ž‘", use_container_width=True)
 
 
 
131
 
132
- if btn:
133
- with st.status("๐Ÿง  AI๊ฐ€ ์‚ฌ์šฉ์ž์˜ ์˜๋„๋ฅผ ๋ถ„์„ ์ค‘์ž…๋‹ˆ๋‹ค...", expanded=True) as status:
134
-
135
- # 1. [๋‡Œ] AI์—๊ฒŒ "์ด๊ฒŒ ๋ฌด์Šจ ๊ธฐ์—…์ด๊ณ  ๊ฒ€์ƒ‰์–ด๋Š” ๋ญ˜๋กœ ํ• ๊นŒ?" ๋ฌผ์–ด๋ด„
136
- target_info = identify_target_with_ai(user_query)
137
-
138
- if target_info:
139
- name = target_info.get('name', 'Unknown')
140
- ticker = target_info.get('ticker', '')
141
- search_keyword = target_info.get('search_keyword', '')
142
-
143
- st.info(f"๐Ÿ’ก AI ํŒŒ์•… ์™„๋ฃŒ!\n- ๊ธฐ์—…๋ช…: **{name}**\n- ํ‹ฐ์ปค: **{ticker}**\n- ๊ฒ€์ƒ‰ ํ‚ค์›Œ๋“œ: **'{search_keyword}'**")
144
-
145
- # 2. [์†๋ฐœ] ๋ฐ์ดํ„ฐ ๋ฐ ๋‰ด์Šค ์ˆ˜์ง‘
146
- st.write("๐Ÿ“‰ ์ฐจํŠธ ๋ฐ์ดํ„ฐ ์ˆ˜์ง‘ ์ค‘...")
147
- hist, src = get_market_data(ticker)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
 
149
- st.write(f"๐Ÿ“ฐ ๋‰ด์Šค ๊ฒ€์ƒ‰ ์ค‘ ('{search_keyword}'๋กœ ๊ฒ€์ƒ‰)...")
150
- news_data = get_news(search_keyword)
151
 
152
- # ๋ฐ์ดํ„ฐ ์ค€๋น„
153
- curr, pct = "N/A", 0
154
- if not hist.empty:
155
- curr = hist['Close'].iloc[-1]
156
- prev = hist['Close'].iloc[-2]
157
- pct = ((curr - prev)/prev)*100
158
- status.update(label="โœ… ๋ถ„์„ ์ค€๋น„ ์™„๋ฃŒ!", state="complete", expanded=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159
  else:
160
- status.update(label="โš ๏ธ ์ฐจํŠธ ๋ฐ์ดํ„ฐ ์—†์Œ (๋‰ด์Šค ๋ถ„์„ ์ง„ํ–‰)", state="complete", expanded=False)
161
-
162
- st.divider()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
 
164
- # ๊ฒฐ๊ณผ ํ™”๋ฉด
165
- m1, m2 = st.columns(2)
166
- m1.metric("Current Price", f"{curr:,.0f}" if isinstance(curr, float) else curr, f"{pct:.2f}%")
167
- m2.metric("Data Source", src)
 
 
 
 
 
 
 
168
 
169
- if not hist.empty:
170
- st.plotly_chart(plot_chart(hist, name, src), use_container_width=True)
171
- else:
172
- st.warning("์ฐจํŠธ ๋ฐ์ดํ„ฐ๋ฅผ ๋ถˆ๋Ÿฌ์˜ค์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค.")
173
 
174
- with st.expander("๐Ÿ“ฐ AI๊ฐ€ ์ฝ์€ ๋‰ด์Šค ์›๋ฌธ ๋ณด๊ธฐ"):
175
- st.text(news_data)
176
 
177
- # 3. [์ž…] ์ตœ์ข… ๋ณด๊ณ 
178
- st.subheader(f"๐Ÿง  AI Insight: {name}")
179
- prompt = f"""
180
- [ROLE] Global Investment Analyst.
181
- [TARGET] {name} ({ticker})
182
- [USER QUERY] "{user_query}"
183
- [DATA] Price: {curr}, Trend: {pct:.2f}%
184
- [NEWS CONTEXT] {news_data}
185
-
186
- [TASK]
187
- 1. Briefly explain what this company does (based on user query context).
188
- 2. Analyze the recent news sentiment.
189
- 3. Provide an investment verdict (Buy/Hold/Sell).
190
-
191
- [LANGUAGE] Korean.
192
- """
193
- messages = [{"role": "user", "content": prompt}]
194
- stream = client.chat.completions.create(model="Qwen/Qwen2.5-72B-Instruct", messages=messages, stream=True)
195
- st.write_stream(parse_stream(stream))
196
-
197
- else:
198
- status.update(label="โŒ ์ธ์‹ ์‹คํŒจ", state="error")
199
- st.error("AI๊ฐ€ ์–ด๋–ค ๊ธฐ์—…์ธ์ง€ ํŒŒ์•…ํ•˜์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค. ์กฐ๊ธˆ ๋” ๊ตฌ์ฒด์ ์œผ๋กœ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”.")
 
11
 
12
  # 1. ํŽ˜์ด์ง€ ์„ค์ •
13
  st.set_page_config(page_title="Pocket Quant AI", page_icon="๐Ÿง ", layout="wide")
 
 
14
 
15
  # 2. ํ† ํฐ ํ™•์ธ
16
  if "HF_TOKEN" in st.secrets:
17
  client = InferenceClient(api_key=st.secrets["HF_TOKEN"])
18
  else:
19
+ st.error("๐Ÿšจ ์„ค์ • ์˜ค๋ฅ˜: Secrets์— 'HF_TOKEN'์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.")
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.
32
+ [QUERY] "{user_query}"
 
 
 
 
33
  [TASK]
34
+ 1. Identify the company (e.g., "๋น„๋‚˜๋ฐ€ํฌ" -> "Vinamilk").
35
+ 2. Find best Ticker (Yahoo format preferred).
36
+ - Vietnam: .VN, Indonesia: .JK, US: Symbol only, Korea: .KS/.KQ
37
+ 3. Create English search keyword for news.
 
 
 
 
38
 
39
+ [OUTPUT JSON]
 
40
  {{
41
+ "name": "English Company Name",
42
  "ticker": "TICKER",
43
+ "search_keyword": "Company Name + 'stock news'"
44
  }}
45
  """
 
46
  messages = [{"role": "user", "content": prompt}]
47
  response = client.chat.completions.create(
48
  model="Qwen/Qwen2.5-72B-Instruct", messages=messages, max_tokens=150
49
  )
 
 
50
  content = response.choices[0].message.content.strip()
51
  content = re.sub(r"```json|```", "", content).strip()
52
  return json.loads(content)
53
+ except: return None
 
 
 
54
 
55
+ # ==============================================================================
56
+ # ๐Ÿ› ๏ธ [ํ•ต์‹ฌ ์—”์ง„ 2] ๋ฐ์ดํ„ฐ ์ˆ˜์ง‘ (Yahoo + FDR + News)
57
+ # ==============================================================================
58
  def get_market_data(ticker):
59
+ # 1. Yahoo
60
  try:
61
  stock = yf.Ticker(ticker)
62
  hist = stock.history(period="3mo")
63
  if not hist.empty: return hist, "Yahoo Finance"
64
  except: pass
65
 
66
+ # 2. FDR (Yahoo ์‹คํŒจ ์‹œ)
67
  try:
 
68
  fdr_symbol = ticker
69
+ if ".VN" in ticker: fdr_symbol = ticker.split('.')[0]
70
  elif ".JK" in ticker: fdr_symbol = f"IDX:{ticker.split('.')[0]}"
71
  elif ".T" in ticker: fdr_symbol = f"TSE:{ticker.split('.')[0]}"
72
 
 
76
  hist = hist.rename(columns={'Close':'Close', 'Open':'Open', 'High':'High', 'Low':'Low', 'Volume':'Volume'})
77
  return hist, "FinanceDataReader"
78
  except: pass
 
79
  return pd.DataFrame(), "None"
80
 
 
81
  def get_news(keyword):
82
  summary = ""
83
  try:
84
  with DDGS() as ddgs:
 
85
  results = ddgs.news(keyword, timelimit="m", max_results=5)
86
  for r in results:
87
  summary += f"[{r.get('date','?')}] {r['title']}\n"
88
+ return summary if summary else "No recent news."
89
+ except: return "News Search Error"
90
 
91
  def parse_stream(stream):
92
  for chunk in stream:
93
  if chunk.choices: yield chunk.choices[0].delta.content or ""
94
 
95
+ # ==============================================================================
96
+ # ๐Ÿ“Š [์‹œ๊ฐํ™”] ์ฐจํŠธ ํ•จ์ˆ˜๋“ค
97
+ # ==============================================================================
98
+ def plot_candle_chart(hist, title, source):
99
  fig = go.Figure(data=[go.Candlestick(x=hist.index, open=hist['Open'], high=hist['High'], low=hist['Low'], close=hist['Close'], name="Price")])
100
+ 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)')
101
+ return fig
102
+
103
+ def plot_bar_chart(df):
104
+ colors = ['#00FF00' if x > 0 else '#FF0000' for x in df['Change(%)']]
105
+ fig = go.Figure(go.Bar(x=df['Name'], y=df['Change(%)'], marker_color=colors, text=df['Change(%)'].apply(lambda x: f"{x:.2f}%")))
106
+ 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)')
107
  return fig
108
 
109
  # ==============================================================================
110
+ # ๐Ÿ’พ [๋ฐ์ดํ„ฐ] ์Šค์บ๋„ˆ์šฉ ๋ฆฌ์ŠคํŠธ (๋ณต๊ตฌ๋จ!)
111
  # ==============================================================================
112
+ TICKER_NAMES = {
113
+ "AAPL": "Apple", "NVDA": "NVIDIA", "TSLA": "Tesla", "AMZN": "Amazon", "MSFT": "Microsoft",
114
+ "005930.KS": "Samsung Elec", "000660.KS": "SK Hynix", "207940.KS": "Samsung Bio",
115
+ "VIC.VN": "Vingroup", "VHM.VN": "Vinhomes", "VNM.VN": "Vinamilk", "VCB.VN": "Vietcombank",
116
+ "BBCA.JK": "BCA", "BBRI.JK": "BRI", "GOTO.JK": "GoTo",
117
+ "7203.T": "Toyota", "6758.T": "Sony", "9984.T": "SoftBank",
118
+ "9988.HK": "Alibaba", "0700.HK": "Tencent", "2330.TW": "TSMC",
119
+ "RELIANCE.NS": "Reliance", "TCS.NS": "TCS"
120
+ }
121
 
122
+ MARKET_SAMPLES = {
123
+ "๐Ÿ‡ป๐Ÿ‡ณ ๋ฒ ํŠธ๋‚จ (Vietnam)": ["VIC.VN", "VHM.VN", "VCB.VN", "VNM.VN", "HPG.VN", "MSN.VN", "GAS.VN"],
124
+ "๐Ÿ‡ฎ๐Ÿ‡ฉ ์ธ๋„๋„ค์‹œ์•„": ["BBCA.JK", "BBRI.JK", "TLKM.JK", "BMRI.JK", "ASII.JK", "GOTO.JK"],
125
+ "๐Ÿ‡ฐ๐Ÿ‡ท ํ•œ๊ตญ (Korea)": ["005930.KS", "000660.KS", "035420.KS", "035720.KS", "005380.KS", "207940.KS", "051910.KS"],
126
+ "๐Ÿ‡บ๐Ÿ‡ธ ๋ฏธ๊ตญ (USA)": ["AAPL", "NVDA", "TSLA", "AMZN", "MSFT", "GOOGL", "META", "AMD", "NFLX"],
127
+ "๐Ÿ‡ฏ๐Ÿ‡ต ์ผ๋ณธ (Japan)": ["7203.T", "6758.T", "9984.T", "8035.T", "6861.T", "7974.T", "9432.T"],
128
+ "๐Ÿ‡จ๐Ÿ‡ณ ์ค‘๊ตญ/ํ™์ฝฉ": ["9988.HK", "0700.HK", "3690.HK", "1211.HK", "1810.HK", "0941.HK"],
129
+ "๐Ÿ‡น๐Ÿ‡ผ ๋Œ€๋งŒ (Taiwan)": ["2330.TW", "2454.TW", "2317.TW", "2308.TW", "2881.TW"],
130
+ "๐Ÿ‡ฎ๐Ÿ‡ณ ์ธ๋„ (India)": ["RELIANCE.NS", "TCS.NS", "HDFCBANK.NS", "INFY.NS", "ICICIBANK.NS"],
131
+ "๐Ÿ‡ธ๐Ÿ‡ฌ ์‹ฑ๊ฐ€ํฌ๋ฅด": ["D05.SI", "O39.SI", "U11.SI", "Z74.SI"],
132
+ "๐Ÿ‡ฒ๐Ÿ‡พ ๋ง๋ ˆ์ด์‹œ์•„": ["1155.KL", "1023.KL", "1295.KL"],
133
+ "๐Ÿ‡น๐Ÿ‡ญ ํƒœ๊ตญ": ["PTT.BK", "AOT.BK", "CPALL.BK"]
134
+ }
135
+
136
+ # ==============================================================================
137
+ # ๐Ÿ–ฅ๏ธ ๋ฉ”์ธ UI & ์‚ฌ์ด๋“œ๋ฐ”
138
+ # ==============================================================================
139
+ with st.sidebar:
140
+ st.title("๐Ÿง  Pocket Quant AI")
141
+ st.divider()
142
+ # ๋ฉ”๋‰ด ๋ถ€ํ™œ!
143
+ menu = st.radio("MENU", ["๐Ÿ” AI ์Šค๋งˆํŠธ ๊ฒ€์ƒ‰", "๐Ÿ“ก ๊ธ€๋กœ๋ฒŒ ์‹œ์žฅ ์Šค์บ๋„ˆ"], index=0)
144
+ st.divider()
145
+ st.caption("Auto-Detect & Multi-Source")
146
+
147
+ # ------------------------------------------------------------------------------
148
+ # ๋ชจ๋“œ 1: AI ์Šค๋งˆํŠธ ๊ฒ€์ƒ‰ (๊ฐœ๋–ก๊ฐ™์ด ๋งํ•ด๋„ ์ฐฐ๋–ก๊ฐ™์ด)
149
+ # ------------------------------------------------------------------------------
150
+ if menu == "๐Ÿ” AI ์Šค๋งˆํŠธ ๊ฒ€์ƒ‰":
151
+ st.subheader("๐Ÿง  ๋ฌด์—‡์ด๋“  ๋ฌผ์–ด๋ณด์„ธ์š” (AI Smart Search)")
152
+ st.caption("์˜ˆ: '๋น„๋‚˜๋ฐ€ํฌ', '๋ฒ ํŠธ๋‚จ ๋นˆ๊ทธ๋ฃน', '์ผ๋ณธ ๋„์š”ํƒ€' ๋“ฑ ํŽธํ•˜๊ฒŒ ์ž…๋ ฅํ•˜์„ธ์š”.")
153
+
154
+ col1, col2 = st.columns([3, 1])
155
+ with col1:
156
+ user_query = st.text_input("๊ฒ€์ƒ‰์–ด ์ž…๋ ฅ", "๋น„๋‚˜๋ฐ€ํฌ", label_visibility="collapsed")
157
+ with col2:
158
+ btn = st.button("๋ถ„์„ ์‹คํ–‰", use_container_width=True)
159
+
160
+ if btn:
161
+ with st.status("๐Ÿง  AI๊ฐ€ ์‚ฌ์šฉ์ž์˜ ์˜๋„๋ฅผ ํ•ด์„ํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค...", expanded=True) as status:
162
 
163
+ # 1. AI ์˜๋„ ํŒŒ์•…
164
+ target_info = identify_target_with_ai(user_query)
165
 
166
+ if target_info:
167
+ name = target_info.get('name', 'Unknown')
168
+ ticker = target_info.get('ticker', '')
169
+ keyword = target_info.get('search_keyword', '')
170
+
171
+ st.info(f"๐Ÿ’ก ๋ถ„์„ ๋Œ€์ƒ: **{name} ({ticker})** | ๊ฒ€์ƒ‰์–ด: '{keyword}'")
172
+
173
+ # 2. ๋ฐ์ดํ„ฐ ์ˆ˜์ง‘
174
+ st.write("๐Ÿ“‰ ์‹œ์žฅ ๋ฐ์ดํ„ฐ ์ˆ˜์ง‘ ์ค‘...")
175
+ hist, src = get_market_data(ticker)
176
+
177
+ st.write("๐Ÿ“ฐ ๊ธ€๋กœ๋ฒŒ ๋‰ด์Šค ์ˆ˜์ง‘ ์ค‘...")
178
+ news_data = get_news(keyword)
179
+
180
+ # ๋ฐ์ดํ„ฐ ์ •๋ฆฌ
181
+ curr, pct = "N/A", 0
182
+ if not hist.empty:
183
+ curr = hist['Close'].iloc[-1]
184
+ prev = hist['Close'].iloc[-2]
185
+ pct = ((curr - prev)/prev)*100
186
+ status.update(label="โœ… ๋ถ„์„ ์™„๋ฃŒ!", state="complete", expanded=False)
187
+ else:
188
+ status.update(label="โš ๏ธ ์ฐจํŠธ ๋ฐ์ดํ„ฐ ์—†์Œ (๋‰ด์Šค๋งŒ ๋ถ„์„)", state="complete", expanded=False)
189
+
190
+ st.divider()
191
+
192
+ # ์‹œ๊ฐํ™”
193
+ m1, m2 = st.columns(2)
194
+ m1.metric("Current Price", f"{curr:,.0f}" if isinstance(curr, float) else curr, f"{pct:.2f}%")
195
+ m2.metric("Source", src)
196
+
197
+ if not hist.empty:
198
+ st.plotly_chart(plot_candle_chart(hist, name, src), use_container_width=True)
199
+ else:
200
+ st.warning("์ฐจํŠธ ๋ฐ์ดํ„ฐ๋ฅผ ๋ถˆ๋Ÿฌ์˜ฌ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")
201
+
202
+ with st.expander("๐Ÿ“ฐ ๋‰ด์Šค ์›๋ฌธ ๋ณด๊ธฐ"):
203
+ st.text(news_data)
204
+
205
+ # 3. ๋ฆฌํฌํŠธ ์ž‘์„ฑ
206
+ st.subheader(f"๐Ÿง  AI Insight: {name}")
207
+ prompt = f"""
208
+ [ROLE] Global Analyst.
209
+ [TARGET] {name} ({ticker})
210
+ [QUERY] "{user_query}"
211
+ [DATA] Price: {curr}, Trend: {pct:.2f}%
212
+ [NEWS] {news_data}
213
+ [TASK] Analyze sentiment and provide investment verdict.
214
+ [LANG] Korean.
215
+ """
216
+ messages = [{"role": "user", "content": prompt}]
217
+ stream = client.chat.completions.create(model="Qwen/Qwen2.5-72B-Instruct", messages=messages, stream=True)
218
+ st.write_stream(parse_stream(stream))
219
+
220
  else:
221
+ status.update(label="โŒ ์ธ์‹ ์‹คํŒจ", state="error")
222
+ st.error("AI๊ฐ€ ๊ธฐ์—…์„ ์ฐพ์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค.")
223
+
224
+ # ------------------------------------------------------------------------------
225
+ # ๋ชจ๋“œ 2: ๊ธ€๋กœ๋ฒŒ ์‹œ์žฅ ์Šค์บ๋„ˆ (Top 10 ๋“ฑ๋ฝ๋ฅ ) - ๋ณต๊ตฌ ์™„๋ฃŒ!
226
+ # ------------------------------------------------------------------------------
227
+ elif menu == "๐Ÿ“ก ๊ธ€๋กœ๋ฒŒ ์‹œ์žฅ ์Šค์บ๋„ˆ":
228
+ st.subheader("๐Ÿ“ก ๊ธ€๋กœ๋ฒŒ ์‹œ์žฅ ์ „๊ด‘ํŒ (Global Scanner)")
229
+
230
+ c1, c2 = st.columns([3, 1])
231
+ with c1:
232
+ target_market = st.selectbox("๊ตญ๊ฐ€ ์„ ํƒ", list(MARKET_SAMPLES.keys()), label_visibility="collapsed")
233
+ with c2:
234
+ scan_btn = st.button("์Šค์บ” ์‹œ์ž‘", use_container_width=True)
235
+
236
+ if scan_btn:
237
+ tickers = MARKET_SAMPLES[target_market]
238
+ with st.spinner(f"{target_market} ์ฃผ์š” ์ข…๋ชฉ ์Šค์บ” ์ค‘..."):
239
+ results = []
240
+ progress = st.progress(0)
241
 
242
+ for i, t in enumerate(tickers):
243
+ # Robust ๋ชจ๋“œ๋กœ ๋ฐ์ดํ„ฐ ์ˆ˜์ง‘ (์•ผํ›„ ์‹คํŒจ์‹œ FDR ์ž๋™ ์‚ฌ์šฉ)
244
+ h, s = get_market_data(t)
245
+ if not h.empty:
246
+ last = h['Close'].iloc[-1]
247
+ prev = h['Close'].iloc[-2]
248
+ pct = ((last - prev)/prev)*100
249
+ # ์ด๋ฆ„ํ‘œ ๋ถ™์ด๊ธฐ
250
+ name = TICKER_NAMES.get(t, t)
251
+ results.append({'Name': name, 'Price': last, 'Change(%)': pct})
252
+ progress.progress((i+1)/len(tickers))
253
 
254
+ if results:
255
+ df = pd.DataFrame(results).sort_values('Change(%)', ascending=False)
 
 
256
 
257
+ # ํžˆํŠธ๋งต
258
+ st.plotly_chart(plot_bar_chart(df), use_container_width=True)
259
 
260
+ # Top/Bottom ๋ฆฌ์ŠคํŠธ
261
+ col_up, col_down = st.columns(2)
262
+ with col_up:
263
+ st.success("๐Ÿ”ฅ ๊ธ‰๋“ฑ Top 10")
264
+ st.dataframe(df.head(10).style.format({"Price": "{:,.2f}", "Change(%)": "{:,.2f}%"}), use_container_width=True)
265
+ with col_down:
266
+ st.error("๐Ÿ’ง ๊ธ‰๋ฝ Top 10")
267
+ st.dataframe(df.tail(10).sort_values('Change(%)').style.format({"Price": "{:,.2f}", "Change(%)": "{:,.2f}%"}), use_container_width=True)
268
+ else:
269
+ st.warning("๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ ธ์˜ค์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค.")