benjamin5607 commited on
Commit
1c4b7cd
·
verified ·
1 Parent(s): fbf1364

Update streamlit_app.py

Browse files
Files changed (1) hide show
  1. streamlit_app.py +167 -223
streamlit_app.py CHANGED
@@ -1,10 +1,13 @@
1
  import streamlit as st
2
  import yfinance as yf
 
3
  import pandas as pd
4
  import requests
5
  import plotly.graph_objects as go
6
  from huggingface_hub import InferenceClient
7
  from duckduckgo_search import DDGS
 
 
8
 
9
  # 1. 페이지 설정
10
  st.set_page_config(
@@ -30,134 +33,120 @@ else:
30
  st.error("🚨 설정 오류: Secrets에 'HF_TOKEN'이 필요합니다.")
31
  st.stop()
32
 
33
- # --- [업그레이드] 심층 뉴스 검색기 (최근 3개월 이슈 수집) ---
34
- def get_company_news_deep(keyword):
35
  """
36
- 단순 뉴스 검색이 아니라, '재무', '합병', '리스크', '전망' 등
37
- 핵심 키워드를 조합하여 다각도로 정보를 긁어옵니다.
 
38
  """
39
- news_summary = ""
 
 
 
40
  try:
41
- with DDGS() as ddgs:
42
- # 1. 일반적인 최신 뉴스 (영어 베이스로 검색해야 정보량이 많음)
43
- # max_results를 10개로 늘려서 정보량을 확보
44
- results_gen = ddgs.text(f"{keyword} stock latest news business", max_results=7)
45
-
46
- # 2. 핵심 이슈 검색 (Earnings, Scandal, Merger)
47
- # 최근 3개월간의 굵직한 사건을 찾기 위해 키워드 추가
48
- results_issues = ddgs.text(f"{keyword} stock quarterly earnings forecast risk", max_results=3)
49
-
50
- # 결과 합치기
51
- all_results = list(results_gen) + list(results_issues)
52
-
53
- for i, r in enumerate(all_results):
54
- # 중복 제거 및 포맷팅
55
- if r['title'] not in news_summary:
56
- news_summary += f"[{i+1}] {r['title']} : {r['body']}\n"
 
 
 
 
 
 
 
 
 
 
 
57
 
58
- return news_summary if news_summary else "No major news found via DuckDuckGo."
 
 
 
 
 
 
 
 
 
 
59
  except Exception as e:
60
- return f"News search error: {e}"
 
 
 
61
 
62
- # --- 티커 매핑 (생략 없이 유지) ---
 
 
 
 
 
 
 
 
 
 
 
63
  TICKER_NAMES = {
64
- # 🇺🇸 미국
65
- "AAPL": "Apple", "NVDA": "NVIDIA", "TSLA": "Tesla", "AMZN": "Amazon", "MSFT": "Microsoft",
66
- "GOOGL": "Google", "AMD": "AMD", "META": "Meta", "NFLX": "Netflix", "INTC": "Intel",
67
- "JPM": "JPMorgan", "V": "Visa", "JNJ": "Johnson&Johnson", "WMT": "Walmart", "PG": "P&G",
68
- "KO": "Coca-Cola", "PEP": "Pepsi", "COST": "Costco", "DIS": "Disney", "XOM": "Exxon",
69
- # 🇰🇷 한국
70
- "005930.KS": "삼성전자", "000660.KS": "SK하이닉스", "035420.KS": "NAVER", "035720.KS": "카카오",
71
- "005380.KS": "현��차", "000270.KS": "기아", "051910.KS": "LG화학", "006400.KS": "삼성SDI",
72
- "105560.KS": "KB금융", "055550.KS": "신한지주", "005490.KS": "POSCO홀딩스", "068270.KS": "셀트리온",
73
- "207940.KS": "삼바", "032830.KQ": "알테오젠", "086520.KQ": "에코프로", "247540.KQ": "에코프로비엠",
74
- # 🇯🇵 일본
75
- "7203.T": "Toyota", "6758.T": "Sony", "9984.T": "SoftBank Grp", "9434.T": "SoftBank Corp",
76
- "8035.T": "Tokyo Elec", "6861.T": "Keyence", "7974.T": "Nintendo", "8306.T": "MUFG",
77
- "9432.T": "NTT", "6501.T": "Hitachi", "6954.T": "Fanuc", "7267.T": "Honda",
78
- # 🇨🇳 중국/홍콩
79
- "9988.HK": "Alibaba", "0700.HK": "Tencent", "3690.HK": "Meituan", "1211.HK": "BYD",
80
- "1810.HK": "Xiaomi", "0941.HK": "China Mobile", "0939.HK": "CCB", "0883.HK": "CNOOC",
81
- # 🇹🇼 대만
82
- "2330.TW": "TSMC", "2454.TW": "MediaTek", "2317.TW": "Foxconn", "2308.TW": "Delta Elec",
83
- # 🇮🇳 인도
84
- "RELIANCE.NS": "Reliance", "TCS.NS": "TCS", "HDFCBANK.NS": "HDFC Bank", "INFY.NS": "Infosys",
85
- # 🇻🇳 베트남 & 동남아
86
- "VNM": "VanEck Vietnam ETF", "VIC.VN": "Vingroup", "VHM.VN": "Vinhomes", "VCB.VN": "Vietcombank",
87
- "BBCA.JK": "BCA", "BBRI.JK": "BRI", "D05.SI": "DBS", "1155.KL": "Maybank", "PTT.BK": "PTT", "SM.PS": "SM Inv"
88
  }
89
 
90
  MARKET_SAMPLES = {
91
- "🇰🇷 한국 (Korea)": ["005930.KS", "000660.KS", "035420.KS", "035720.KS", "005380.KS", "000270.KS", "051910.KS", "006400.KS", "105560.KS", "068270.KS"],
92
- "🇺🇸 미국 (USA)": ["AAPL", "NVDA", "TSLA", "AMZN", "MSFT", "GOOGL", "AMD", "META", "NFLX", "INTC", "JPM", "V", "KO"],
93
- "🇯🇵 일본 (Japan)": ["7203.T", "6758.T", "9984.T", "8035.T", "6861.T", "7974.T", "8306.T", "6501.T"],
94
- "🇨🇳 중국/홍콩": ["9988.HK", "0700.HK", "3690.HK", "1211.HK", "1810.HK", "0941.HK"],
95
- "🇹🇼 대만 (Taiwan)": ["2330.TW", "2454.TW", "2317.TW", "2308.TW"],
96
- "🇮🇳 인도 (India)": ["RELIANCE.NS", "TCS.NS", "HDFCBANK.NS", "INFY.NS"],
97
- "🇻🇳 베트남 (Vietnam)": ["VNM", "VIC.VN", "VHM.VN", "VCB.VN", "VNM.VN", "HPG.VN"],
98
- "🇮🇩 인도네시아": ["BBCA.JK", "BBRI.JK", "TLKM.JK", "BMRI.JK", "ASII.JK"],
99
- "🇸🇬 싱가포르": ["D05.SI", "O39.SI", "U11.SI", "Z74.SI"],
100
- "🇲🇾 말레이시아": ["1155.KL", "1023.KL", "1295.KL", "5183.KL"],
101
- "🇹🇭 태국": ["PTT.BK", "AOT.BK", "CPALL.BK", "ADVANC.BK"],
102
- "🇵🇭 필리핀": ["SM.PS", "SMPH.PS", "BDO.PS", "ALI.PS"]
103
  }
104
 
105
- # --- 족보 및 검색 헬퍼 ---
106
  GLOBAL_TICKER_MAP = {
107
- "TSMC": "2330.TW", "ALIBABA": "9988.HK", "RELIANCE": "RELIANCE.NS",
108
- "TOYOTA": "7203.T", "SONY": "6758.T", "SAMSUNG": "005930.KS",
109
- "VINFAST": "VFS", "COUPANG": "CPNG", "GRAB": "GRAB", "SHOPEE": "SE"
110
  }
111
 
112
  def get_ticker_from_ai(name):
113
  try:
114
- prompt = f"Find Yahoo Finance ticker for '{name}'. Return ONLY ticker. No text."
115
  messages = [{"role": "user", "content": prompt}]
116
- response = client.chat.completions.create(
117
- model="Qwen/Qwen2.5-72B-Instruct", messages=messages, max_tokens=20
118
- )
119
  return response.choices[0].message.content.strip().replace("`", "").upper().split()[0]
120
  except: return None
121
 
122
  def search_ticker(query):
123
- q = query.upper().strip()
124
- return GLOBAL_TICKER_MAP.get(q, get_ticker_from_ai(query))
125
-
126
- def get_naver_stock_info(code):
127
- try:
128
- code_num = code.split('.')[0]
129
- url = f"https://finance.naver.com/item/main.naver?code={code_num}"
130
- headers = {'User-Agent': 'Mozilla/5.0'}
131
- res = requests.get(url, headers=headers)
132
- dfs = pd.read_html(res.text, encoding='euc-kr')
133
- info = {}
134
- for df in dfs:
135
- if "PER" in str(df):
136
- for i in range(len(df)):
137
- for j in range(len(df.columns)):
138
- if "PER" in str(df.iloc[i,j]) and "EPS" not in str(df.iloc[i,j]):
139
- try: info['trailingPE'] = float(df.iloc[i,j+1])
140
- except: pass
141
- if "PBR" in str(df.iloc[i,j]):
142
- try: info['priceToBook'] = float(df.iloc[i,j+1])
143
- except: pass
144
- return info
145
- except: return {}
146
 
147
  def parse_stream(stream):
148
  for chunk in stream:
149
- if chunk.choices and len(chunk.choices) > 0:
150
- delta = chunk.choices[0].delta
151
- if hasattr(delta, 'content') and delta.content:
152
- yield delta.content.replace("```markdown", "").replace("```", "")
153
 
154
- # --- 차트 함수 ---
155
- def plot_candle_chart(hist, title):
156
  fig = go.Figure(data=[go.Candlestick(
157
  x=hist.index, open=hist['Open'], high=hist['High'], low=hist['Low'], close=hist['Close'], name="Price"
158
  )])
159
  fig.update_layout(
160
- title=dict(text=f"{title} Trend", x=0), height=350, margin=dict(l=10, r=10, t=40, b=10),
 
161
  xaxis_rangeslider_visible=False, template="plotly_dark",
162
  paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)'
163
  )
@@ -175,153 +164,108 @@ def plot_bar_chart(df):
175
  )
176
  return fig
177
 
178
- # ==============================================================================
179
- # 사이드바
180
- # ==============================================================================
181
  with st.sidebar:
182
  st.header("🌏 Pocket Quant Pro")
183
- st.write("AI Global Investment")
184
  st.divider()
185
  menu = st.radio("MENU", ["🔍 종목 분석 (AI Analysis)", "📡 시장 스캐너 (Market Watch)"], index=0)
186
  st.divider()
187
- st.caption("Data: Yahoo + Naver + Global News")
188
 
189
- # ==============================================================================
190
- # 1. 종목 분석 모드 (심층 뉴스 적용)
191
- # ==============================================================================
192
  if "종목 분석" in menu:
193
- st.subheader("🔍 AI Investment Analyst (Deep Dive)")
194
  c1, c2 = st.columns([3, 1])
195
- with c1: user_input = st.text_input("Ticker", "Samsung", label_visibility="collapsed", placeholder="종목명 (예: 삼성전자, Tesla)")
196
  with c2: analyze_btn = st.button("Deep Analyze", use_container_width=True)
197
 
198
  if analyze_btn:
199
- with st.status("🚀 1단계: 글로벌 뉴스 데이터를 수집합니다...", expanded=True) as status:
200
  ticker = search_ticker(user_input)
201
 
202
  if ticker:
203
- try:
204
- # 1. 뉴스 심층 수집
205
- st.write(f"🌍 전 세계 웹을 뒤져서 '{user_input}'의 최근 3개월 이슈를 찾습니다...")
206
- # 검색어에 'English' 같은 제한을 두지 않고, AI가 알아서 해석하게끔 원문 수집
207
- news_data = get_company_news_deep(user_input)
 
 
 
 
 
 
208
 
209
- # 2. 주가 데이터 수집
210
- st.write(f"📈 '{ticker}' 재무/차트 데이터 로딩 중...")
211
- stock = yf.Ticker(ticker)
212
- hist = stock.history(period="3mo")
213
 
214
- if not hist.empty:
215
- curr = hist['Close'].iloc[-1]
216
- prev = hist['Close'].iloc[-2]
217
- change_pct = ((curr - prev) / prev) * 100
218
- vol = hist['Volume'].iloc[-1]
219
-
220
- info = stock.info
221
- if ".KS" in ticker or ".KQ" in ticker: info.update(get_naver_stock_info(ticker))
222
-
223
- per = info.get('trailingPE', 'N/A')
224
- pbr = info.get('priceToBook', 'N/A')
225
- currency = info.get('currency', '')
226
-
227
- status.update(label="✅ 분석 준비 완료! AI가 리포트를 작성합니다.", state="complete", expanded=False)
228
-
229
- st.divider()
230
- m1, m2, m3, m4 = st.columns(4)
231
- m1.metric("Price", f"{curr:,.2f} {currency}", f"{change_pct:.2f}%")
232
- m2.metric("PER", f"{per}")
233
- m3.metric("PBR", f"{pbr}")
234
- m4.metric("Vol", f"{vol:,.0f}")
235
-
236
- st.plotly_chart(plot_candle_chart(hist, ticker), use_container_width=True)
237
-
238
- # --- 뉴스 펼쳐보기 ---
239
- with st.expander("🌍 AI가 수집한 다국어 뉴스 원문 보기 (클릭)"):
240
- st.text(news_data)
241
- st.caption("※ 위 뉴스들은 DuckDuckGo에서 실시간으로 수집된 원문입니다.")
242
-
243
- # --- AI 심층 분석 프롬프트 ---
244
- st.subheader(f"🧠 Deep Insight: {user_input}")
245
- prompt = f"""
246
- [ROLE]
247
- You are a Polyglot Global Investment Analyst (Korean/English/Chinese proficient).
248
-
249
- [TASK]
250
- Perform a deep-dive analysis on {user_input} ({ticker}) for a Korean investor.
251
- Integrate Financial Data with the 'Narrative' from recent news (approx. past 3 months).
252
-
253
- [FINANCIAL DATA]
254
- - Price: {curr} {currency} ({change_pct:.2f}%)
255
- - PER: {per} (Valuation)
256
- - PBR: {pbr}
257
-
258
- [GLOBAL NEWS CONTEXT (Unstructured)]
259
- {news_data}
260
-
261
- [INSTRUCTIONS]
262
- 1. **News Analysis (Core):** Identify key events (Earnings, Mergers, Regulatory issues, Product launches) from the news.
263
- - If news is in English/Foreign languages, translate the essence to Korean.
264
- - Filter out noise; focus on what impacts the stock price.
265
- 2. **Valuation Check:** Is the stock cheap or expensive given the news context?
266
- 3. **Strategy:** Provide a clear Buy/Sell/Hold opinion based on the "Data + Narrative".
267
-
268
- **OUTPUT FORMAT:**
269
- - Use Markdown. No code blocks.
270
- - Language: **Korean (한국어)**.
271
- - Tone: Professional yet easy to understand.
272
- """
273
- messages = [{"role": "user", "content": prompt}]
274
- stream = client.chat.completions.create(model="Qwen/Qwen2.5-72B-Instruct", messages=messages, stream=True)
275
- with st.container(border=True): st.write_stream(parse_stream(stream))
276
 
277
- else: status.update(label="❌ 데이터 없음", state="error"); st.error("차트 데이터가 없습니다.")
278
- except Exception as e: status.update(label="❌ 에러", state="error"); st.error(f"Error: {e}")
279
- else: status.update(label="❌ 검색 실패", state="error"); st.error("종목을 찾을 수 없습니다.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
280
 
281
- # ==============================================================================
282
- # 2. 시장 스캐너
283
- # ==============================================================================
284
  elif "시장 스캐너" in menu:
285
- st.subheader("📡 Global Market Watch (Top 10)")
286
 
287
  col_sel, col_btn = st.columns([3, 1])
288
  with col_sel: target_market = st.selectbox("Select Country", list(MARKET_SAMPLES.keys()), label_visibility="collapsed")
289
- with col_btn: scan_trigger = st.button("Scan Market", use_container_width=True)
290
 
291
  if scan_trigger:
292
  tickers = MARKET_SAMPLES[target_market]
293
- with st.spinner(f"Scanning {target_market} stocks..."):
294
- try:
295
- data = yf.download(tickers, period="1mo", progress=False, threads=False)['Close']
296
- if not data.empty:
297
- current_prices = []
298
- changes = []
299
- valid_tickers = []
300
- for ticker in tickers:
301
- if ticker in data.columns:
302
- series = data[ticker].dropna()
303
- if len(series) >= 2:
304
- last = series.iloc[-1]
305
- prev = series.iloc[-2]
306
- pct = ((last - prev)/prev)*100
307
- current_prices.append(last)
308
- changes.append(pct)
309
- valid_tickers.append(ticker)
310
-
311
- df = pd.DataFrame({'Ticker': valid_tickers, 'Price': current_prices, 'Change(%)': changes})
312
- if not df.empty:
313
- df.set_index('Ticker', inplace=True)
314
- df['Name'] = [TICKER_NAMES.get(x, x) for x in df.index]
315
- df = df[['Name', 'Price', 'Change(%)']].sort_values('Change(%)', ascending=False)
316
-
317
- st.plotly_chart(plot_bar_chart(df), use_container_width=True)
318
- c1, c2 = st.columns(2)
319
- with c1:
320
- st.success(f"🔥 {target_market} Top 10 Gainers")
321
- st.dataframe(df.head(10).style.format({"Price": "{:,.2f}", "Change(%)": "{:,.2f}%"}), use_container_width=True)
322
- with c2:
323
- st.error(f"💧 {target_market} Top 10 Losers")
324
- st.dataframe(df.tail(10).sort_values('Change(%)').style.format({"Price": "{:,.2f}", "Change(%)": "{:,.2f}%"}), use_container_width=True)
325
- else: st.warning("유효한 가격 정보가 없습니다.")
326
- else: st.warning("데이터 다운로드 실패.")
327
- except Exception as e: st.error(f"Scan failed: {e}")
 
1
  import streamlit as st
2
  import yfinance as yf
3
+ import FinanceDataReader as fdr
4
  import pandas as pd
5
  import requests
6
  import plotly.graph_objects as go
7
  from huggingface_hub import InferenceClient
8
  from duckduckgo_search import DDGS
9
+ import json
10
+ import datetime
11
 
12
  # 1. 페이지 설정
13
  st.set_page_config(
 
33
  st.error("🚨 설정 오류: Secrets에 'HF_TOKEN'이 필요합니다.")
34
  st.stop()
35
 
36
+ # --- [핵심 기능] 3중 데이터 수집 (Yahoo -> FDR -> Web) ---
37
+ def get_stock_data_robust(ticker, period_days=90):
38
  """
39
+ 1. Yahoo Finance 시도
40
+ 2. 실패 시 FinanceDataReader(Investing.com/Naver) 시도
41
+ 3. 데이터프레임(History)과 현재가 리턴
42
  """
43
+ hist = pd.DataFrame()
44
+ source = ""
45
+
46
+ # [1단계] Yahoo Finance
47
  try:
48
+ stock = yf.Ticker(ticker)
49
+ # 야후는 period 인자 사용
50
+ hist = stock.history(period="3mo")
51
+ if not hist.empty:
52
+ return hist, "Yahoo Finance"
53
+ except:
54
+ pass
55
+
56
+ # [2단계] FinanceDataReader (Plan B)
57
+ # 야후 티커를 FDR용 심볼로 변환해야 함
58
+ fdr_symbol = ticker
59
+ exchange = None
60
+
61
+ # 베트남: VIC.VN -> VIC (HOSE)
62
+ if ".VN" in ticker:
63
+ fdr_symbol = ticker.split('.')[0]
64
+ exchange = 'VN' # Vietnam
65
+ # 인도네시아: .JK -> Investing.com 심볼 매핑 필요 (FDR은 'IDX:BBCA' 형식을 씀)
66
+ elif ".JK" in ticker:
67
+ fdr_symbol = f"IDX:{ticker.split('.')[0]}"
68
+ # 태국, 말레이시아 등
69
+ elif ".BK" in ticker: fdr_symbol = f"SET:{ticker.split('.')[0]}"
70
+ elif ".KL" in ticker: fdr_symbol = f"KLS:{ticker.split('.')[0]}"
71
+
72
+ try:
73
+ # 최근 3개월 날짜 계산
74
+ start_date = (datetime.datetime.now() - datetime.timedelta(days=period_days)).strftime('%Y-%m-%d')
75
 
76
+ # FDR로 데이터 긁어오기
77
+ if exchange == 'VN':
78
+ # 베트남은 별도 처리
79
+ hist = fdr.DataReader(fdr_symbol, start_date) # 베트남은 거래소 코드 없이 종목코드만 넣으면 잘 됨 (KRX/Naver소스)
80
+ else:
81
+ hist = fdr.DataReader(fdr_symbol, start_date)
82
+
83
+ if not hist.empty:
84
+ # FDR 컬럼명을 Yahoo 포맷(Open, High, Low, Close, Volume)으로 통일
85
+ hist = hist.rename(columns={'Close': 'Close', 'Open': 'Open', 'High': 'High', 'Low': 'Low', 'Volume': 'Volume'})
86
+ return hist, "FinanceDataReader (Investing/Naver)"
87
  except Exception as e:
88
+ print(f"FDR Failed: {e}")
89
+ pass
90
+
91
+ return pd.DataFrame(), "None"
92
 
93
+ # --- [보조 기능] 뉴스 검색 ---
94
+ def get_recent_news(keyword):
95
+ news_summary = ""
96
+ try:
97
+ with DDGS() as ddgs:
98
+ results = ddgs.news(f"{keyword} stock business", timelimit="m", max_results=5)
99
+ for i, r in enumerate(results):
100
+ news_summary += f"[{r.get('date', '?')}] {r['title']}\n"
101
+ return news_summary if news_summary else "No recent news."
102
+ except: return "News Search Error"
103
+
104
+ # --- 티커 매핑 ---
105
  TICKER_NAMES = {
106
+ "AAPL": "Apple", "NVDA": "NVIDIA", "TSLA": "Tesla", "005930.KS": "삼성전자",
107
+ "VIC.VN": "Vingroup", "VHM.VN": "Vinhomes", "VCB.VN": "Vietcombank",
108
+ "BBCA.JK": "BCA", "BBRI.JK": "BRI", "GOTO.JK": "GoTo",
109
+ "1155.KL": "Maybank", "PTT.BK": "PTT"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  }
111
 
112
  MARKET_SAMPLES = {
113
+ "🇻🇳 베트남 (Vietnam)": ["VIC.VN", "VHM.VN", "VCB.VN", "VNM.VN", "HPG.VN", "MSN.VN"],
114
+ "🇮🇩 인도네시아": ["BBCA.JK", "BBRI.JK", "TLKM.JK", "BMRI.JK", "ASII.JK", "GOTO.JK"],
115
+ "🇰🇷 한국": ["005930.KS", "000660.KS", "035420.KS", "207940.KS"],
116
+ "🇺🇸 미국": ["AAPL", "NVDA", "TSLA", "MSFT", "GOOGL", "AMD"],
117
+ "🇨🇳 중국/홍콩": ["9988.HK", "0700.HK", "3690.HK", "1211.HK"],
118
+ "🇯🇵 일본": ["7203.T", "6758.T", "9984.T", "8035.T"]
 
 
 
 
 
 
119
  }
120
 
 
121
  GLOBAL_TICKER_MAP = {
122
+ "TSMC": "2330.TW", "VINGROUP": "VIC.VN", "VINFAST": "VFS",
123
+ "SAMSUNG": "005930.KS", "TOYOTA": "7203.T"
 
124
  }
125
 
126
  def get_ticker_from_ai(name):
127
  try:
128
+ prompt = f"Find Yahoo Finance ticker for '{name}'. Return ONLY ticker."
129
  messages = [{"role": "user", "content": prompt}]
130
+ response = client.chat.completions.create(model="Qwen/Qwen2.5-72B-Instruct", messages=messages, max_tokens=20)
 
 
131
  return response.choices[0].message.content.strip().replace("`", "").upper().split()[0]
132
  except: return None
133
 
134
  def search_ticker(query):
135
+ return GLOBAL_TICKER_MAP.get(query.upper().strip(), get_ticker_from_ai(query))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
 
137
  def parse_stream(stream):
138
  for chunk in stream:
139
+ if chunk.choices:
140
+ yield chunk.choices[0].delta.content or ""
 
 
141
 
142
+ # --- 차트 그리기 ---
143
+ def plot_candle_chart(hist, title, source):
144
  fig = go.Figure(data=[go.Candlestick(
145
  x=hist.index, open=hist['Open'], high=hist['High'], low=hist['Low'], close=hist['Close'], name="Price"
146
  )])
147
  fig.update_layout(
148
+ title=dict(text=f"{title} Trend (Source: {source})", x=0),
149
+ height=350, margin=dict(l=10, r=10, t=40, b=10),
150
  xaxis_rangeslider_visible=False, template="plotly_dark",
151
  paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)'
152
  )
 
164
  )
165
  return fig
166
 
167
+ # --- 사이드바 ---
 
 
168
  with st.sidebar:
169
  st.header("🌏 Pocket Quant Pro")
 
170
  st.divider()
171
  menu = st.radio("MENU", ["🔍 종목 분석 (AI Analysis)", "📡 시장 스캐너 (Market Watch)"], index=0)
172
  st.divider()
173
+ st.caption("Auto-Fallback: Yahoo -> FDR")
174
 
175
+ # --- 종목 분석 ---
 
 
176
  if "종목 분석" in menu:
177
+ st.subheader("🔍 AI Investment Analyst (Historical Data Mining)")
178
  c1, c2 = st.columns([3, 1])
179
+ with c1: user_input = st.text_input("Ticker", "Vingroup", label_visibility="collapsed", placeholder="종목명")
180
  with c2: analyze_btn = st.button("Deep Analyze", use_container_width=True)
181
 
182
  if analyze_btn:
183
+ with st.status("🚀 3중 데이터 수집 시스템 가동...", expanded=True) as status:
184
  ticker = search_ticker(user_input)
185
 
186
  if ticker:
187
+ st.write(f"🎯 타겟 확인: {ticker}")
188
+
189
+ # [핵심] Robust Data Fetching
190
+ hist, data_source = get_stock_data_robust(ticker)
191
+
192
+ # 뉴스 수집
193
+ news_data = get_recent_news(user_input)
194
+
195
+ if not hist.empty:
196
+ # 데이터 확보 성공
197
+ status.update(label=f"✅ 데이터 확보 성공! (출처: {data_source})", state="complete", expanded=False)
198
 
199
+ curr = hist['Close'].iloc[-1]
200
+ prev = hist['Close'].iloc[-2]
201
+ change_pct = ((curr - prev) / prev) * 100
202
+ vol = hist['Volume'].iloc[-1] if 'Volume' in hist.columns else 0
203
 
204
+ st.divider()
205
+
206
+ # 상단 메트릭
207
+ m1, m2, m3 = st.columns(3)
208
+ m1.metric("Price", f"{curr:,.0f}", f"{change_pct:.2f}%")
209
+ m2.metric("Source", data_source)
210
+ m3.metric("Volume", f"{vol:,.0f}")
211
+
212
+ # 차트 그리기 (FDR 데이터로도 그려짐!)
213
+ st.plotly_chart(plot_candle_chart(hist, ticker, data_source), use_container_width=True)
214
+
215
+ # 뉴스 & AI 분석
216
+ with st.expander(f"📰 '{user_input}' 관련 최신 뉴스 보기"):
217
+ st.text(news_data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218
 
219
+ st.subheader(f"🧠 Deep Insight: {user_input}")
220
+ prompt = f"""
221
+ [ROLE] Global Analyst. [TASK] Analyze {user_input} ({ticker}).
222
+ [DATA] Price: {curr}, Trend: {change_pct:.2f}% (Source: {data_source})
223
+ [NEWS] {news_data}
224
+ [LANG] Korean.
225
+ [OUT] Markdown. 1.Technical Analysis 2.News Sentiment 3.Strategy
226
+ """
227
+ messages = [{"role": "user", "content": prompt}]
228
+ stream = client.chat.completions.create(model="Qwen/Qwen2.5-72B-Instruct", messages=messages, stream=True)
229
+ with st.container(border=True): st.write_stream(parse_stream(stream))
230
+
231
+ else:
232
+ status.update(label="❌ 데이터 수집 실패", state="error")
233
+ st.error("모든 소스(Yahoo, Investing, Naver)에서 데이터를 찾을 수 없습니다.")
234
+ st.warning("가능성 1: 티커가 잘못됨\n가능성 2: 해당 국가 데이터가 유료화됨")
235
+ else:
236
+ status.update(label="❌ 티커 못 찾음", state="error")
237
 
238
+ # --- 시장 스캐너 ---
 
 
239
  elif "시장 스캐너" in menu:
240
+ st.subheader("📡 Global Market Watch")
241
 
242
  col_sel, col_btn = st.columns([3, 1])
243
  with col_sel: target_market = st.selectbox("Select Country", list(MARKET_SAMPLES.keys()), label_visibility="collapsed")
244
+ with col_btn: scan_trigger = st.button("Scan", use_container_width=True)
245
 
246
  if scan_trigger:
247
  tickers = MARKET_SAMPLES[target_market]
248
+ with st.spinner(f"Scanning {target_market} stocks (Robust Mode)..."):
249
+ results = []
250
+
251
+ # 스캐너도 Robust 모드로 동작 (조금 느려도 확실하게)
252
+ progress_bar = st.progress(0)
253
+ for i, ticker in enumerate(tickers):
254
+ hist, src = get_stock_data_robust(ticker, period_days=5)
255
+ if not hist.empty:
256
+ last = hist['Close'].iloc[-1]
257
+ prev = hist['Close'].iloc[-2]
258
+ pct = ((last - prev)/prev)*100
259
+ name = TICKER_NAMES.get(ticker, ticker)
260
+ results.append({'Name': name, 'Price': last, 'Change(%)': pct})
261
+ progress_bar.progress((i + 1) / len(tickers))
262
+
263
+ if results:
264
+ df = pd.DataFrame(results).sort_values('Change(%)', ascending=False)
265
+ st.plotly_chart(plot_bar_chart(df), use_container_width=True)
266
+
267
+ c1, c2 = st.columns(2)
268
+ with c1: st.success("🔥 Top Gainers"); st.dataframe(df.head(10).style.format({"Price": "{:,.2f}", "Change(%)": "{:,.2f}%"}), use_container_width=True)
269
+ with c2: st.error("💧 Top Losers"); st.dataframe(df.tail(10).sort_values('Change(%)').style.format({"Price": "{:,.2f}", "Change(%)": "{:,.2f}%"}), use_container_width=True)
270
+ else:
271
+ st.warning("데이터 수집 실패.")