Spaces:
Sleeping
Sleeping
Update streamlit_app.py
Browse files- 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 |
-
# --- [
|
| 34 |
-
def
|
| 35 |
"""
|
| 36 |
-
|
| 37 |
-
|
|
|
|
| 38 |
"""
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
| 40 |
try:
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
except Exception as e:
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
-
# ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
TICKER_NAMES = {
|
| 64 |
-
|
| 65 |
-
"
|
| 66 |
-
"
|
| 67 |
-
"
|
| 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 |
-
"
|
| 92 |
-
"
|
| 93 |
-
"
|
| 94 |
-
"
|
| 95 |
-
"
|
| 96 |
-
"
|
| 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", "
|
| 108 |
-
"
|
| 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.
|
| 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 |
-
|
| 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
|
| 150 |
-
|
| 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),
|
|
|
|
| 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("
|
| 188 |
|
| 189 |
-
#
|
| 190 |
-
# 1. 종목 분석 모드 (심층 뉴스 적용)
|
| 191 |
-
# ==============================================================================
|
| 192 |
if "종목 분석" in menu:
|
| 193 |
-
st.subheader("🔍 AI Investment Analyst (
|
| 194 |
c1, c2 = st.columns([3, 1])
|
| 195 |
-
with c1: user_input = st.text_input("Ticker", "
|
| 196 |
with c2: analyze_btn = st.button("Deep Analyze", use_container_width=True)
|
| 197 |
|
| 198 |
if analyze_btn:
|
| 199 |
-
with st.status("🚀
|
| 200 |
ticker = search_ticker(user_input)
|
| 201 |
|
| 202 |
if ticker:
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 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 |
-
|
| 278 |
-
|
| 279 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
|
| 281 |
-
#
|
| 282 |
-
# 2. 시장 스캐너
|
| 283 |
-
# ==============================================================================
|
| 284 |
elif "시장 스캐너" in menu:
|
| 285 |
-
st.subheader("📡 Global Market Watch
|
| 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
|
| 290 |
|
| 291 |
if scan_trigger:
|
| 292 |
tickers = MARKET_SAMPLES[target_market]
|
| 293 |
-
with st.spinner(f"Scanning {target_market} stocks..."):
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 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("데이터 수집 실패.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|