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

Update streamlit_app.py

Browse files
Files changed (1) hide show
  1. streamlit_app.py +195 -168
streamlit_app.py CHANGED
@@ -20,81 +20,131 @@ else:
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
 
73
- start = (datetime.datetime.now() - datetime.timedelta(days=90)).strftime('%Y-%m-%d')
74
- hist = fdr.DataReader(fdr_symbol, start)
75
  if not hist.empty:
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)')
@@ -107,13 +157,14 @@ def plot_bar_chart(df):
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"
@@ -122,148 +173,124 @@ TICKER_NAMES = {
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("๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ ธ์˜ค์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  st.stop()
21
 
22
  # ==============================================================================
23
+ # ๐Ÿ•ต๏ธ [์ƒ์กด ๊ธฐ์ˆ ] ์›น ๊ฒ€์ƒ‰์œผ๋กœ ๊ฐ€๊ฒฉ ๊ฐ•์ œ ์ถ”์ถœ (Last Resort)
24
  # ==============================================================================
25
+ def scrape_price_from_web(name, ticker):
26
  """
27
+ ์•ผํ›„/FDR ๋ชจ๋‘ ์‹คํŒจํ–ˆ์„ ๋•Œ, ๊ฒ€์ƒ‰ ์—”์ง„์„ ๋Œ๋ ค์„œ ๊ฐ€๊ฒฉ์„ ํ…์ŠคํŠธ์—์„œ ๋œฏ์–ด๋ƒ„.
28
  """
29
  try:
30
+ with DDGS() as ddgs:
31
+ # ๊ฒ€์ƒ‰์–ด: "Vinamilk stock price today"
32
+ query = f"{name} {ticker} stock price quote today"
33
+ results = ddgs.text(query, max_results=3)
34
+
35
+ # ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ ํ…์ŠคํŠธ ํ•ฉ์น˜๊ธฐ
36
+ text_blob = " ".join([r['body'] for r in results])
37
+
38
+ # ์ •๊ทœํ‘œํ˜„์‹์œผ๋กœ ์ˆซ์ž ์ฐพ๊ธฐ (๊ฐ„๋‹จํ•œ ๋กœ์ง)
39
+ # ์˜ˆ: "trading at 45,000" ๋˜๋Š” "Price: 123.45"
40
+ # (์ •๋ฐ€๋„๋Š” AI๋ณด๋‹ค ๋‚ฎ์ง€๋งŒ ์†๋„๋ฅผ ์œ„ํ•ด ์ •๊ทœ์‹ ์‚ฌ์šฉ)
41
+ # ๋ฒ ํŠธ๋‚จ ๋™(VND) ๊ฐ™์€ ํฐ ์ˆซ์ž๋‚˜ ์†Œ์ˆ˜์  ์ˆซ์ž ๋งค์นญ
42
+ match = re.search(r'(\d{1,3}(,\d{3})*(\.\d+)?)', text_blob)
43
+
44
+ if match:
45
+ price_str = match.group(0)
46
+ # ์‰ผํ‘œ ์ œ๊ฑฐ ํ›„ float ๋ณ€ํ™˜ ์‹œ๋„
47
+ try:
48
+ price = float(price_str.replace(",", ""))
49
+ return price, 0.0 # ๋“ฑ๋ฝ๋ฅ ์€ ์ฐพ๊ธฐ ์–ด๋ ค์šฐ๋ฏ€๋กœ 0์œผ๋กœ ๋‘ 
50
+ except: pass
51
+
52
+ return None, None
53
+ except:
54
+ return None, None
55
 
56
  # ==============================================================================
57
+ # ๐Ÿ› ๏ธ [ํ•ต์‹ฌ ์—”์ง„] 3๋‹จ๊ณ„ ๋ฐ์ดํ„ฐ ์ˆ˜์ง‘ (FDR -> Yahoo -> Web)
58
  # ==============================================================================
59
+ def get_price_data_robust(ticker, name):
60
+ """
61
+ 1. FDR (Investing.com/Naver) -> ๋ฒ ํŠธ๋‚จ/ํ•œ๊ตญ์— ๊ฐ•๋ ฅ
62
+ 2. Yahoo (๋ฏธ๊ตญ/์ผ๋ณธ์— ๊ฐ•๋ ฅ)
63
+ 3. Web Search (์ตœํ›„์˜ ์ˆ˜๋‹จ)
64
+ """
65
+ # [1๋‹จ๊ณ„] FinanceDataReader (๋™๋‚จ์•„/ํ•œ๊ตญ ์šฐ์„ )
 
 
66
  try:
67
  fdr_symbol = ticker
68
+ if ".VN" in ticker: fdr_symbol = ticker.split('.')[0] # ๋ฒ ํŠธ๋‚จ (HOSE)
69
+ elif ".JK" in ticker: fdr_symbol = f"IDX:{ticker.split('.')[0]}" # ์ธ๋„๋„ค์‹œ์•„
70
+ elif ".KS" in ticker or ".KQ" in ticker: fdr_symbol = ticker.split('.')[0] # ํ•œ๊ตญ
71
 
72
+ # ์ตœ๊ทผ 5์ผ์น˜๋งŒ ๊ฐ€์ ธ์˜ด (์†๋„ ์ตœ์ ํ™”)
73
+ hist = fdr.DataReader(fdr_symbol, start=(datetime.datetime.now() - datetime.timedelta(days=10)))
74
  if not hist.empty:
75
+ curr = hist['Close'].iloc[-1]
76
+ prev = hist['Close'].iloc[-2] if len(hist) > 1 else curr
77
+ pct = ((curr - prev)/prev)*100
78
+ return curr, pct, "FDR"
79
  except: pass
80
+
81
+ # [2๋‹จ๊ณ„] Yahoo Finance (๋ฏธ๊ตญ/์ผ๋ณธ ์šฐ์„ )
82
+ try:
83
+ stock = yf.Ticker(ticker)
84
+ # fast_info๊ฐ€ ๋” ๋น ๋ฆ„
85
+ price = stock.fast_info.last_price
86
+ prev = stock.fast_info.previous_close
87
+ if price and prev:
88
+ pct = ((price - prev)/prev)*100
89
+ return price, pct, "Yahoo"
90
+ except: pass
91
+
92
+ # [3๋‹จ๊ณ„] ์ตœํ›„์˜ ์ˆ˜๋‹จ: ์›น ๊ฒ€์ƒ‰ (Qwen์ด ์‹œํ‚จ ๊ฒ€์ƒ‰)
93
+ # ์ฐจํŠธ ๋ฐ์ดํ„ฐ๋Š” ์—†์ง€๋งŒ ์Šค์บ๋„ˆ ๋นˆ์นธ์€ ์ฑ„์›Œ์•ผ ํ•จ
94
+ price, pct = scrape_price_from_web(name, ticker)
95
+ if price is not None:
96
+ return price, pct if pct else 0.0, "Web Search ๐Ÿ•ต๏ธ"
97
+
98
+ return None, None, "Fail"
99
+
100
+ # ==============================================================================
101
+ # ๐Ÿง  [์—”์ง„ 1] AI ์ง€๋Šฅํ˜• ๊ฒ€์ƒ‰
102
+ # ==============================================================================
103
+ def identify_target_with_ai(user_query):
104
+ try:
105
+ prompt = f"""
106
+ [ROLE] Financial Entity Resolver. [QUERY] "{user_query}"
107
+ [TASK] Identify company, ticker, and news keyword.
108
+ [OUTPUT JSON] {{ "name": "English Name", "ticker": "TICKER", "search_keyword": "Keyword" }}
109
+ """
110
+ messages = [{"role": "user", "content": prompt}]
111
+ response = client.chat.completions.create(model="Qwen/Qwen2.5-72B-Instruct", messages=messages, max_tokens=150)
112
+ content = re.sub(r"```json|```", "", response.choices[0].message.content.strip()).strip()
113
+ return json.loads(content)
114
+ except: return None
115
 
116
+ # ๋‰ด์Šค ๊ฒ€์ƒ‰
117
  def get_news(keyword):
118
  summary = ""
119
  try:
120
  with DDGS() as ddgs:
121
  results = ddgs.news(keyword, timelimit="m", max_results=5)
122
+ for r in results: summary += f"[{r.get('date','?')}] {r['title']}\n"
 
123
  return summary if summary else "No recent news."
124
+ except: return "Search Error"
125
 
126
  def parse_stream(stream):
127
  for chunk in stream:
128
  if chunk.choices: yield chunk.choices[0].delta.content or ""
129
 
130
+ # ์ฐจํŠธ (๋ถ„์„์šฉ)
131
+ def get_chart_data(ticker):
132
+ try:
133
+ fdr_symbol = ticker
134
+ if ".VN" in ticker: fdr_symbol = ticker.split('.')[0]
135
+ elif ".JK" in ticker: fdr_symbol = f"IDX:{ticker.split('.')[0]}"
136
+ start = (datetime.datetime.now() - datetime.timedelta(days=90)).strftime('%Y-%m-%d')
137
+ hist = fdr.DataReader(fdr_symbol, start)
138
+ if not hist.empty:
139
+ return hist.rename(columns={'Close':'Close', 'Open':'Open', 'High':'High', 'Low':'Low'}), "FDR"
140
+ except: pass
141
+ try:
142
+ hist = yf.Ticker(ticker).history(period="3mo")
143
+ if not hist.empty: return hist, "Yahoo"
144
+ except: pass
145
+ return pd.DataFrame(), "None"
146
+
147
+ # ์‹œ๊ฐํ™” ํ•จ์ˆ˜
148
  def plot_candle_chart(hist, title, source):
149
  fig = go.Figure(data=[go.Candlestick(x=hist.index, open=hist['Open'], high=hist['High'], low=hist['Low'], close=hist['Close'], name="Price")])
150
  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)')
 
157
  return fig
158
 
159
  # ==============================================================================
160
+ # ๐Ÿ’พ [๋ฐ์ดํ„ฐ]
161
  # ==============================================================================
162
+ # ๋งคํ•‘ ๋ฐ์ดํ„ฐ (์Šค์บ๋„ˆ ํ‘œ์‹œ์šฉ)
163
  TICKER_NAMES = {
164
  "AAPL": "Apple", "NVDA": "NVIDIA", "TSLA": "Tesla", "AMZN": "Amazon", "MSFT": "Microsoft",
165
  "005930.KS": "Samsung Elec", "000660.KS": "SK Hynix", "207940.KS": "Samsung Bio",
166
+ "VIC.VN": "Vingroup", "VHM.VN": "Vinhomes", "VNM.VN": "Vinamilk", "VCB.VN": "Vietcombank", "GAS.VN": "PV Gas",
167
+ "BBCA.JK": "BCA", "BBRI.JK": "BRI", "GOTO.JK": "GoTo", "ASII.JK": "Astra Intl",
168
  "7203.T": "Toyota", "6758.T": "Sony", "9984.T": "SoftBank",
169
  "9988.HK": "Alibaba", "0700.HK": "Tencent", "2330.TW": "TSMC",
170
  "RELIANCE.NS": "Reliance", "TCS.NS": "TCS"
 
173
  MARKET_SAMPLES = {
174
  "๐Ÿ‡ป๐Ÿ‡ณ ๋ฒ ํŠธ๋‚จ (Vietnam)": ["VIC.VN", "VHM.VN", "VCB.VN", "VNM.VN", "HPG.VN", "MSN.VN", "GAS.VN"],
175
  "๐Ÿ‡ฎ๐Ÿ‡ฉ ์ธ๋„๋„ค์‹œ์•„": ["BBCA.JK", "BBRI.JK", "TLKM.JK", "BMRI.JK", "ASII.JK", "GOTO.JK"],
176
+ "๐Ÿ‡ฐ๐Ÿ‡ท ํ•œ๊ตญ (Korea)": ["005930.KS", "000660.KS", "035420.KS", "035720.KS", "005380.KS", "207940.KS"],
177
+ "๐Ÿ‡บ๐Ÿ‡ธ ๋ฏธ๊ตญ (USA)": ["AAPL", "NVDA", "TSLA", "AMZN", "MSFT", "GOOGL", "META", "AMD"],
178
+ "๐Ÿ‡ฏ๐Ÿ‡ต ์ผ๋ณธ (Japan)": ["7203.T", "6758.T", "9984.T", "8035.T", "6861.T", "7974.T"],
179
+ "๐Ÿ‡จ๐Ÿ‡ณ ์ค‘๊ตญ/ํ™์ฝฉ": ["9988.HK", "0700.HK", "3690.HK", "1211.HK", "1810.HK"],
180
+ "๐Ÿ‡น๐Ÿ‡ผ ๋Œ€๋งŒ (Taiwan)": ["2330.TW", "2454.TW", "2317.TW", "2308.TW"],
181
+ "๐Ÿ‡ฎ๐Ÿ‡ณ ์ธ๋„ (India)": ["RELIANCE.NS", "TCS.NS", "HDFCBANK.NS", "INFY.NS"]
 
 
 
182
  }
183
 
184
  # ==============================================================================
185
+ # ๐Ÿ–ฅ๏ธ UI
186
  # ==============================================================================
187
  with st.sidebar:
188
  st.title("๐Ÿง  Pocket Quant AI")
189
  st.divider()
 
190
  menu = st.radio("MENU", ["๐Ÿ” AI ์Šค๋งˆํŠธ ๊ฒ€์ƒ‰", "๐Ÿ“ก ๊ธ€๋กœ๋ฒŒ ์‹œ์žฅ ์Šค์บ๋„ˆ"], index=0)
 
 
191
 
192
+ # --- 1. AI ์Šค๋งˆํŠธ ๊ฒ€์ƒ‰ ---
 
 
193
  if menu == "๐Ÿ” AI ์Šค๋งˆํŠธ ๊ฒ€์ƒ‰":
194
+ st.subheader("๐Ÿง  ๋ฌด์—‡์ด๋“  ๋ฌผ์–ด๋ณด์„ธ์š”")
195
+ c1, c2 = st.columns([3, 1])
196
+ with c1: query = st.text_input("๊ฒ€์ƒ‰์–ด", "๋ฒ ํŠธ๋‚จ ๋นˆ๊ทธ๋ฃน", label_visibility="collapsed")
197
+ with c2: btn = st.button("๋ถ„์„", use_container_width=True)
 
 
 
 
198
 
199
  if btn:
200
+ with st.status("๐Ÿง  AI ๊ฐ€๋™ ์ค‘...", expanded=True) as status:
201
+ info = identify_target_with_ai(query)
202
+ if info:
203
+ name, ticker, key = info.get('name'), info.get('ticker'), info.get('search_keyword')
204
+ st.info(f"ํƒ€๊ฒŸ: **{name} ({ticker})** | ํ‚ค์›Œ๋“œ: {key}")
 
 
 
 
205
 
206
+ h, src = get_chart_data(ticker) # ์ฐจํŠธ์šฉ ๋ฐ์ดํ„ฐ
207
+ news = get_news(key)
208
 
 
 
 
 
 
 
 
 
209
  curr, pct = "N/A", 0
210
+ if not h.empty:
211
+ curr = h['Close'].iloc[-1]
212
+ pct = ((curr - h['Close'].iloc[-2])/h['Close'].iloc[-2])*100
213
+ status.update(label="โœ… ๋ถ„์„ ์™„๋ฃŒ", state="complete", expanded=False)
 
214
  else:
215
+ # ์ฐจํŠธ ์—†์œผ๋ฉด ์›น ๊ฒ€์ƒ‰ ์‹œ๋„
216
+ c_web, p_web, s_web = get_price_data_robust(ticker, name)
217
+ if c_web:
218
+ curr, pct, src = c_web, p_web, s_web
219
+ status.update(label="โš ๏ธ ์ฐจํŠธ ์—†์Œ (์›น ๋ฐ์ดํ„ฐ ์‚ฌ์šฉ)", state="complete", expanded=False)
220
+ else:
221
+ status.update(label="โŒ ๋ฐ์ดํ„ฐ ์—†์Œ", state="complete", expanded=False)
222
 
223
  st.divider()
 
 
224
  m1, m2 = st.columns(2)
225
+ m1.metric("Price", f"{curr:,.0f}" if isinstance(curr, (int, float)) else curr, f"{pct:.2f}%")
226
  m2.metric("Source", src)
227
 
228
+ if not h.empty: st.plotly_chart(plot_candle_chart(h, name, src), use_container_width=True)
229
+ else: st.warning(f"์ฐจํŠธ๋ฅผ ๊ทธ๋ฆด ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. (Source: {src})")
 
 
 
 
 
230
 
231
+ with st.expander("๋‰ด์Šค ๋ณด๊ธฐ"): st.text(news)
 
 
 
 
 
 
 
 
 
 
 
 
 
232
 
233
+ st.subheader(f"๐Ÿง  Insight: {name}")
234
+ prompt = f"[ROLE] Analyst. [TARGET] {name} ({ticker}). [DATA] Price:{curr}, Trend:{pct:.2f}%. [NEWS] {news}. [TASK] Analyze & Verdict. [LANG] Korean."
235
+ msg = [{"role": "user", "content": prompt}]
236
+ stream = client.chat.completions.create(model="Qwen/Qwen2.5-72B-Instruct", messages=msg, stream=True)
237
+ st.write_stream(parse_stream(stream))
238
+ else: st.error("์ธ์‹ ์‹คํŒจ")
239
 
240
+ # --- 2. ๊ธ€๋กœ๋ฒŒ ์‹œ์žฅ ์Šค์บ๋„ˆ (Total War Mode) ---
 
 
241
  elif menu == "๐Ÿ“ก ๊ธ€๋กœ๋ฒŒ ์‹œ์žฅ ์Šค์บ๋„ˆ":
242
+ st.subheader("๐Ÿ“ก ๊ธ€๋กœ๋ฒŒ ์‹œ์žฅ ์ „๊ด‘ํŒ (Total War Mode)")
243
+ st.caption("์•ผํ›„ -> FDR -> ์›น ๊ฒ€์ƒ‰ 3๋‹จ๊ณ„๋ฅผ ๊ฑฐ์ณ ๋นˆ์นธ ์—†์ด ๋ฐ์ดํ„ฐ๋ฅผ ์ฑ„์›๋‹ˆ๋‹ค. (์†๋„๊ฐ€ ์กฐ๊ธˆ ๋А๋ฆด ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค)")
244
 
245
  c1, c2 = st.columns([3, 1])
246
+ with c1: target = st.selectbox("๊ตญ๊ฐ€", list(MARKET_SAMPLES.keys()))
247
+ with c2: scan = st.button("์Šค์บ” ์‹œ์ž‘")
248
+
249
+ if scan:
250
+ tickers = MARKET_SAMPLES[target]
251
+ results = []
252
+
253
+ # ํ”„๋กœ๊ทธ๋ ˆ์Šค ๋ฐ”
254
+ bar = st.progress(0)
255
+ status_text = st.empty()
256
 
257
+ for i, t in enumerate(tickers):
258
+ name_display = TICKER_NAMES.get(t, t)
259
+ status_text.text(f"Scanning {name_display} ({t})...")
 
 
260
 
261
+ # [ํ•ต์‹ฌ] 3๋‹จ๊ณ„ ์ง‘์š”ํ•œ ๋ฐ์ดํ„ฐ ์ˆ˜์ง‘ ํ•จ์ˆ˜ ํ˜ธ์ถœ
262
+ price, pct, src = get_price_data_robust(t, name_display)
 
 
 
 
 
 
 
 
 
263
 
264
+ if price is not None:
265
+ results.append({
266
+ 'Name': name_display,
267
+ 'Ticker': t,
268
+ 'Price': price,
269
+ 'Change(%)': pct,
270
+ 'Source': src # ์ถœ์ฒ˜๋„ ๊ธฐ๋ก (FDR, Yahoo, Web...)
271
+ })
 
 
 
 
 
 
272
  else:
273
+ # ์ •๋ง ์•„๋ฌด๋ฆฌ ๋’ค์ ธ๋„ ์—†์œผ๋ฉด N/A๋กœ๋ผ๋„ ํ‘œ์‹œ
274
+ results.append({'Name': name_display, 'Ticker': t, 'Price': 0, 'Change(%)': 0, 'Source': 'Fail'})
275
+
276
+ bar.progress((i+1)/len(tickers))
277
+
278
+ status_text.empty()
279
+
280
+ if results:
281
+ df = pd.DataFrame(results).sort_values('Change(%)', ascending=False)
282
+
283
+ # ํžˆํŠธ๋งต
284
+ st.plotly_chart(plot_bar_chart(df), use_container_width=True)
285
+
286
+ # ํ‘œ์‹œํ•  ์ปฌ๋Ÿผ ์ •๋ฆฌ
287
+ disp_cols = ['Name', 'Price', 'Change(%)', 'Source']
288
+
289
+ c_up, c_down = st.columns(2)
290
+ with c_up:
291
+ st.success("๐Ÿ”ฅ Top Gainers")
292
+ st.dataframe(df.head(10)[disp_cols].style.format({"Price": "{:,.2f}", "Change(%)": "{:,.2f}%"}), use_container_width=True)
293
+ with c_down:
294
+ st.error("๐Ÿ’ง Top Losers")
295
+ st.dataframe(df.tail(10)[disp_cols].sort_values('Change(%)').style.format({"Price": "{:,.2f}", "Change(%)": "{:,.2f}%"}), use_container_width=True)
296
+ else: st.warning("๋ฐ์ดํ„ฐ ์ˆ˜์ง‘ ์‹คํŒจ")